repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
Lyuu17/plugin_sdk
plugin_III/game_III/cDMAudio.h
<gh_stars>0 /* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" class PLUGIN_API cDMAudio { public: SUPPORTED_10EN_11EN_STEAM void PlayFrontEndSound(unsigned short v1, unsigned int v2); SUPPORTED_10EN_11EN_STEAM void PlayOneShot(int v1, unsigned short v2, float v3); }; extern cDMAudio &DMAudio; #include "meta/meta.cDMAudio.h"
Lyuu17/plugin_sdk
plugin_III/game_III/CFont.h
/* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CRGBA.h" #include "CRect.h" #include "CFontDetails.h" #include "CSprite2d.h" class PLUGIN_API CFont { public: // variables static CFontDetails &Details; static CSprite2d *Sprite; static short &NewLine; // funcs SUPPORTED_10EN_11EN static void DrawFonts(); // get next ' ' character in a string SUPPORTED_10EN_11EN static wchar_t* GetNextSpace(const wchar_t* str); SUPPORTED_10EN_11EN static int GetNumberLines(float x, float y, const wchar_t* text); SUPPORTED_10EN_11EN static float GetStringWidth(const wchar_t* str, bool sentence); SUPPORTED_10EN_11EN static CRect* GetTextRect(CRect* rect_out, float x, float y, const wchar_t* text); SUPPORTED_10EN_11EN static void InitPerFrame(); // CFont initialisation SUPPORTED_10EN_11EN static void Initialise(); SUPPORTED_10EN_11EN static wchar_t* ParseToken(wchar_t* str); // this adds a single character into rendering buffer SUPPORTED_10EN_11EN static void PrintChar(float x, float y, short character); SUPPORTED_10EN_11EN static void PrintString(float x, float y, const wchar_t* text); SUPPORTED_10EN_11EN static void PrintString(float x, float y, const wchar_t* start, const wchar_t* end, float arg4); // like a 'global' font alpha, multiplied with each text alpha (from SetColor) SUPPORTED_10EN_11EN static void SetAlphaFade(float alpha); SUPPORTED_10EN_11EN static void SetBackGroundOnlyTextOff(); SUPPORTED_10EN_11EN static void SetBackGroundOnlyTextOn(); // sets background color SUPPORTED_10EN_11EN static void SetBackgroundColor(CRGBA color); SUPPORTED_10EN_11EN static void SetBackgroundOff(); SUPPORTED_10EN_11EN static void SetBackgroundOn(); SUPPORTED_10EN_11EN static void SetCentreOff(); SUPPORTED_10EN_11EN static void SetCentreOn(); // set line width at center SUPPORTED_10EN_11EN static void SetCentreSize(float size); // set text color SUPPORTED_10EN_11EN static void SetColor(CRGBA color); // drop color is used for text shadow and text outline SUPPORTED_10EN_11EN static void SetDropColor(CRGBA color); // set shadow size SUPPORTED_10EN_11EN static void SetDropShadowPosition(short value); // set text style SUPPORTED_10EN_11EN static void SetFontStyle(short style); SUPPORTED_10EN_11EN static void SetJustifyOff(); SUPPORTED_10EN_11EN static void SetJustifyOn(); SUPPORTED_10EN_11EN static void SetPropOff(); SUPPORTED_10EN_11EN static void SetPropOn(); SUPPORTED_10EN_11EN static void SetRightJustifyOff(); SUPPORTED_10EN_11EN static void SetRightJustifyOn(); SUPPORTED_10EN_11EN static void SetRightJustifyWrap(float value); // text scaling SUPPORTED_10EN_11EN static void SetScale(float width, float height); // set text rotation angle SUPPORTED_10EN_11EN static void SetSlant(float value); // set text rotation point SUPPORTED_10EN_11EN static void SetSlantRefPoint(float x, float y); // set line width at right SUPPORTED_10EN_11EN static void SetWrapx(float value); // CFont closing SUPPORTED_10EN_11EN static void Shutdown(); SUPPORTED_10EN_11EN static short character_code(unsigned char character); SUPPORTED_10EN_11EN static char* GetNextSpace(const char* str); SUPPORTED_10EN_11EN static int GetNumberLines(float x, float y, const char* text); SUPPORTED_10EN_11EN static float GetStringWidth(const char* str, bool sentence); SUPPORTED_10EN_11EN static CRect* GetTextRect(CRect* rect_out, float x, float y, const char* text); SUPPORTED_10EN_11EN static char* ParseToken(char* str); // this adds a single character into rendering buffer SUPPORTED_10EN_11EN static void PrintChar(float x, float y, char character); SUPPORTED_10EN_11EN static void PrintString(float x, float y, const char* text); SUPPORTED_10EN_11EN static void PrintString(float x, float y, const char* start, const char* end, float arg4); }; SUPPORTED_10EN_11EN void AsciiToUnicode(char const* str_ascii, wchar_t* str_unicode); SUPPORTED_10EN_11EN int UnicodeStrlen(wchar_t const* str); SUPPORTED_10EN_11EN char* UnicodeToAscii(wchar_t* str_unicode); extern char *aStr; #include "meta/meta.CFont.h"
Lyuu17/plugin_sdk
plugin_III/game_III/meta/meta.CCoronas.h
/* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "PluginBase.h" namespace plugin { META_BEGIN(CCoronas::DoSunAndMoon) static int address; static int global_address; static const int id = 0x4FA380; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4FA380, 0x4FA460, 0x4FA3F0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CCoronas::Init) static int address; static int global_address; static const int id = 0x4F9F90; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4F9F90, 0x4FA070, 0x4FA000>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN_OVERLOADED(CCoronas::RegisterCorona, void(*)(unsigned int, unsigned char, unsigned char, unsigned char, unsigned char, CVector const&, float, float, RwTexture*, unsigned char, unsigned char, unsigned char, unsigned char, float)) static int address; static int global_address; static const int id = 0x4FA0E0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4FA0E0, 0x4FA1C0, 0x4FA150>; using refs_t = RefList<>; using def_t = void(unsigned int, unsigned char, unsigned char, unsigned char, unsigned char, CVector const&, float, float, RwTexture*, unsigned char, unsigned char, unsigned char, unsigned char, float); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<unsigned int, unsigned char, unsigned char, unsigned char, unsigned char, CVector const&, float, float, RwTexture*, unsigned char, unsigned char, unsigned char, unsigned char, float>, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13>; META_END META_BEGIN_OVERLOADED(CCoronas::RegisterCorona, void(*)(unsigned int, unsigned char, unsigned char, unsigned char, unsigned char, CVector const&, float, float, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, float)) static int address; static int global_address; static const int id = 0x4FA080; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4FA080, 0x4FA160, 0x4FA0F0>; using refs_t = RefList<>; using def_t = void(unsigned int, unsigned char, unsigned char, unsigned char, unsigned char, CVector const&, float, float, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, float); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<unsigned int, unsigned char, unsigned char, unsigned char, unsigned char, CVector const&, float, float, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, float>, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13>; META_END META_BEGIN(CCoronas::Render) static int address; static int global_address; static const int id = 0x4F8FB0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4F8FB0, 0x4F9C20, 0x4F9BB0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CCoronas::RenderReflections) static int address; static int global_address; static const int id = 0x4F9B40; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4F9B40, 0x4F9C20, 0x4F9BB0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CCoronas::Shutdown) static int address; static int global_address; static const int id = 0x4FA050; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4FA050, 0x4FA130, 0x4FA0C0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CCoronas::Update) static int address; static int global_address; static const int id = 0x4F8EC0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4F8EC0, 0x4F8FA0, 0x4F8F30>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CCoronas::UpdateCoronaCoors) static int address; static int global_address; static const int id = 0x4FA2D0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4FA2D0, 0x4FA3B0, 0x4FA340>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END }
Lyuu17/plugin_sdk
plugin_III/game_III/meta/meta.CParticle.h
<filename>plugin_III/game_III/meta/meta.CParticle.h<gh_stars>0 /* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "PluginBase.h" namespace plugin { CTOR_META_BEGIN(CParticle) static int address; static int global_address; static const int id = 0x43CD40; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50C410, 0x50C500, 0x50C490>; using refs_t = RefList<>; using def_t = CParticle *(CParticle *); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CParticle *>, 0>; META_END DTOR_META_BEGIN(CParticle) static int address; static int global_address; static const int id = 0x43CD30; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50C420, 0x50C510, 0x50C4A0>; using refs_t = RefList<>; using def_t = void(CParticle *); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CParticle *>, 0>; META_END META_BEGIN(CParticle::ReloadConfig) static int address; static int global_address; static const int id = 0x50C430; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50C430, 0x50C520, 0x50C4B0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CParticle::Initialise) static int address; static int global_address; static const int id = 0x50C570; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50C570, 0x50C660, 0x50C5F0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CParticle::Shutdown) static int address; static int global_address; static const int id = 0x50CF40; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50CF40, 0x50D030, 0x50CFC0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN_OVERLOADED(CParticle::AddParticle, CParticle *(*)(tParticleType, CVector const&, CVector const&, CEntity*, float, int, int, int, int)) static int address; static int global_address; static const int id = 0x50D140; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50D140, 0x50D330, 0x50D2C0>; using refs_t = RefList<>; using def_t = CParticle *(tParticleType, CVector const&, CVector const&, CEntity*, float, int, int, int, int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<tParticleType,CVector const &,CVector const &,CEntity *,float,int,int,int,int>, 0,1,2,3,4,5,6,7,8>; META_END META_BEGIN_OVERLOADED(CParticle::AddParticle, CParticle *(*)(tParticleType, CVector const&, CVector const&, CEntity*, float, RwRGBA const&, int, int, int, int)) static int address; static int global_address; static const int id = 0x50D190; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50D190, 0x50D380, 0x50D310>; using refs_t = RefList<>; using def_t = CParticle *(tParticleType, CVector const &, CVector const &, CEntity *, float, RwRGBA const *, int, int, int, int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<tParticleType, CVector const&, CVector const&, CEntity*, float, RwRGBA const&, int, int, int, int>, 0,1,2,3,4,5,6,7,8,9>; META_END META_BEGIN(CParticle::Update) static int address; static int global_address; static const int id = 0x50DCF0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50DCF0, 0x50DEE0, 0x50DE70>; // total references count: 10en (4), 11en (4), steam (4) using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CParticle::Render) static int address; static int global_address; static const int id = 0x50EE20; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50EE20, 0x50F010, 0x50EFA0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CParticle::RemovePSystem) static int address; static int global_address; static const int id = 0x50F6E0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50F6E0, 0x50F8D0, 0x50F860>; using refs_t = RefList<>; using def_t = void(tParticleType); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<tParticleType>, 0>; META_END META_BEGIN(CParticle::RemoveParticle) static int address; static int global_address; static const int id = 0x50F720; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50F720, 0x50F910, 0x50F8A0>; using refs_t = RefList<>; static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<CParticle*, CParticle*, tParticleSystemData*>, 0, 1, 2>; META_END META_BEGIN(CParticle::AddJetExplosion) static int address; static int global_address; static const int id = 0x50F760; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50F760, 0x50F950, 0x50F8E0>; using refs_t = RefList<>; static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<CVector const&, float, float>, 0, 1, 2>; META_END META_BEGIN(CParticle::AddYardieDoorSmoke) static int address; static int global_address; static const int id = 0x50FAA0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x50FAA0, 0x50FC90, 0x50FC20>; using refs_t = RefList<>; static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<CVector const&, CMatrix const&>, 0, 1>; META_END template <> SUPPORTED_10EN_11EN_STEAM inline CParticle *operator_new<CParticle>() { void *objData = operator new(sizeof(CParticle)); CParticle *obj = reinterpret_cast<CParticle *>(objData); plugin::CallMethodDynGlobal<CParticle *>(ctor_gaddr(CParticle), obj); return obj; } template <> SUPPORTED_10EN_11EN_STEAM inline CParticle *operator_new_array<CParticle>(unsigned int objCount) { void *objData = operator new(sizeof(CParticle) * objCount + 4); *reinterpret_cast<unsigned int *>(objData) = objCount; CParticle *objArray = reinterpret_cast<CParticle *>(reinterpret_cast<unsigned int>(objData) + 4); for (unsigned int i = 0; i < objCount; i++) plugin::CallMethodDynGlobal<CParticle *>(ctor_gaddr(CParticle), &objArray[i]); return objArray; } template <> SUPPORTED_10EN_11EN_STEAM inline void operator_delete<CParticle>(CParticle *obj) { if (obj == nullptr) return; plugin::CallMethodDynGlobal<CParticle *>(dtor_gaddr(CParticle), obj); operator delete(obj); } template <> SUPPORTED_10EN_11EN_STEAM inline void operator_delete_array<CParticle>(CParticle *objArray) { if (objArray == nullptr) return; void *objData = reinterpret_cast<void *>(reinterpret_cast<char *>(objArray) - 4); unsigned int arraySize = *reinterpret_cast<unsigned int *>(objData); for (unsigned int i = 0; i < arraySize; i++) plugin::CallMethodDynGlobal<CParticle *>(dtor_gaddr(CParticle), &objArray[i]); operator delete(objData); } }
Lyuu17/plugin_sdk
plugin_III/game_III/cAudioManager.h
/* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "cPoliceRadio.h" #include "CVector.h" #define NUM_SOUNDS_SAMPLES_BANKS 2 #define NUM_SOUNDS_SAMPLES_SLOTS 27 #define NUM_SCRIPT_MAX_ENTITIES 40 #define NUM_AUDIOENTITIES 200 #define NUM_AUDIO_REFLECTIONS 5 enum eAudioType { AUDIOTYPE_PHYSICAL = 0x0, AUDIOTYPE_EXPLOSION = 0x1, AUDIOTYPE_FIRE = 0x2, AUDIOTYPE_WEATHER = 0x3, AUDIOTYPE_CRANE = 0x4, AUDIOTYPE_SCRIPTOBJECT = 0x5, AUDIOTYPE_BRIDGE = 0x6, AUDIOTYPE_COLLISION = 0x7, AUDIOTYPE_FRONTEND = 0x8, AUDIOTYPE_PROJECTILE = 0x9, AUDIOTYPE_GARAGE = 0xA, AUDIOTYPE_FIREHYDRANT = 0xB, AUDIOTYPE_WATERCANNON = 0xC, AUDIOTYPE_POLICERADIO = 0xD, MAX_AUDIOTYPES = 0xE, }; struct cVehicleParams { unsigned char field_4; char _pad[3]; float m_fDistanceSquared; class CVehicle* m_pVehicle; class cTransmission* m_pTransmission; unsigned int m_nVehicleAudioIndex; float m_fSpeed; }; struct tSound { unsigned int m_AudioEntity; unsigned int m_nIndex; unsigned int m_nCurSampleIndex; unsigned char field_C; char field_D; char tmp0[2]; unsigned int field_10; unsigned int m_nSampleFreq; unsigned char m_nVolume; char tmp1[3]; float m_fDistance; unsigned int field_20; int m_nLoopStartOffset; int m_nLoopEndOffset; unsigned char _oldVolume; char tmp2[3]; float field_30; float field_34; char field_38; char tmp3[3]; CVector m_vecPosition; bool m_bUseReverb; char field_49; char field_4A; unsigned char field_4B; int field_4C; char field_50; char field_51; char tmp6[2]; int field_54; unsigned char field_58; char tmp7[3]; }; static_assert(sizeof(tSound) == 92, "tSound: error"); struct tAudioEntity { eAudioType m_AudioType; void* m_Object; bool m_bActive; unsigned char m_nStatus; unsigned short m_anSfxId[4]; char _pad0[2]; float field_14[4]; unsigned char field_24; char _pad1[3]; }; static_assert(sizeof(tAudioEntity) == 40, "tAudioEntity: error"); struct tPedComment { unsigned int m_nSampleIndex; int field_4; CVector vecPosition; float m_fDistance; unsigned char m_nVolume; unsigned char field_19; char _pad0[2]; }; static_assert(sizeof(tPedComment) == 28, "tPedComment: error"); struct cPedComments { tPedComment arr[40]; unsigned char m_aIndex[40]; unsigned char field_488[2]; unsigned char m_nBaseIndex; char field_48B; }; static_assert(sizeof(cPedComments) == 1164, "cPedComments: error"); struct cAudioCollision { class CEntity* m_pPhysEntity; class CEntity* m_pPhysColling; unsigned char m_nSurfaceTypeA; unsigned char m_nSurfaceTypeB; char _pad0[2]; float m_fCollisionPower; float m_fVelocity; CVector m_vecPosition; float m_fDistance; unsigned int field_24; }; static_assert(sizeof(tPedComment) == 28, "tPedComment: error"); struct cAudioCollisionManager { cAudioCollision arr1[10]; cAudioCollision arr2[10]; unsigned char field_4A9C[10]; unsigned char field_4AA6; char _pad0[1]; cAudioCollision m_Queue; }; static_assert(sizeof(cPedComments) == 1164, "cPedComments: error"); class cMissionAudio { public: CVector m_vecPos; bool m_bPredefinedProperties; int m_nSampleIndex; unsigned char m_nLoadingStatus; unsigned char m_nPlayStatus; unsigned char field_22; // todo find a name int m_nMissionAudioCounter; bool m_bIsPlayed; }; static_assert(sizeof(cMissionAudio) == 32, "cMissionAudio: error"); class cAudioScriptObjectManager { public: int m_anScriptObjectEntityIndices[NUM_SCRIPT_MAX_ENTITIES]; int m_nScriptObjectEntityTotal; cAudioScriptObjectManager() { m_nScriptObjectEntityTotal = 0; } ~cAudioScriptObjectManager() { m_nScriptObjectEntityTotal = 0; } }; class PLUGIN_API cAudioManager { public: bool m_bInitialised; char field_1; // unused bool m_bFifthFrameFlag; unsigned char m_nActiveSamples; char field_4; // unused bool m_bDynamicAcousticModelingStatus; float m_fSpeedOfSound; bool m_bTimerJustReset; unsigned int m_nTimer; tSound m_sQueueSample; unsigned char m_nActiveSampleQueue; tSound m_asSamples[NUM_SOUNDS_SAMPLES_BANKS][NUM_SOUNDS_SAMPLES_SLOTS]; unsigned char m_abSampleQueueIndexTable[NUM_SOUNDS_SAMPLES_BANKS][NUM_SOUNDS_SAMPLES_SLOTS]; unsigned char m_SampleRequestQueuesStatus[NUM_SOUNDS_SAMPLES_BANKS]; tSound m_asActiveSamples[NUM_SOUNDS_SAMPLES_SLOTS]; tAudioEntity m_asAudioEntities[NUM_AUDIOENTITIES]; int m_anAudioEntityIndices[NUM_AUDIOENTITIES]; int m_nAudioEntitiesTotal; CVector m_avecReflectionsPos[NUM_AUDIO_REFLECTIONS]; float m_afReflectionsDistances[NUM_AUDIO_REFLECTIONS]; cAudioScriptObjectManager m_sAudioScriptObjectManager; cPedComments m_sPedComments; int m_nFireAudioEntity; int m_nWaterCannonEntity; int m_nPoliceChannelEntity; cPoliceRadioQueue m_sPoliceRadioQueue; int m_nFrontEndEntity; int m_nCollisionEntity; cAudioCollisionManager m_sCollisionManager; int m_nProjectileEntity; int m_nBridgeEntity; cMissionAudio m_sMissionAudio; int m_anRandomTable[5]; unsigned char m_nTimeSpent; bool m_bUserPause; bool m_bPreviousUserPause; int m_FrameCounter; cAudioManager(); ~cAudioManager(); bool UsesSiren(unsigned int index); // see eVehicleIndex bool UsesSirenSwitching(unsigned int index); // see eVehicleIndex SUPPORTED_10EN_11EN_STEAM float GetDistanceSquared(CVector const& vec); SUPPORTED_10EN_11EN_STEAM int CalculateDistance(unsigned char& a1, float a2); SUPPORTED_10EN_11EN_STEAM unsigned char ComputeVolume(unsigned char a1, float a2, float a3); SUPPORTED_10EN_11EN_STEAM int RandomDisplacement(unsigned int a1); SUPPORTED_10EN_11EN_STEAM void ProcessLoopingScriptObject(unsigned char a1); SUPPORTED_11EN void AddSampleToRequestedQueue(); }; //VALIDATE_SIZE(cAudioManager, 0x4B14); extern cAudioManager &gAudioManager; #include "meta/meta.cAudioManager.h"
Lyuu17/plugin_sdk
plugin_III/game_III/CColPoint.h
<gh_stars>0 /* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CVector.h" class PLUGIN_API CColPoint { public: CVector m_vecPoint; float field_C; CVector m_vecNormal; float field_1C; unsigned char m_nSurfaceTypeA; unsigned char m_nPieceTypeA; unsigned char m_nSurfaceTypeB; unsigned char m_nPieceTypeB; float m_fCollisionRadius; CColPoint& operator=(CColPoint const &right) { m_vecPoint = right.m_vecPoint; field_C = right.field_C; m_vecNormal = right.m_vecNormal; field_1C = right.field_1C; m_nSurfaceTypeA = right.m_nSurfaceTypeA; m_nPieceTypeA = right.m_nPieceTypeA; m_nSurfaceTypeB = right.m_nSurfaceTypeB; m_nPieceTypeB = right.m_nPieceTypeB; m_fCollisionRadius = right.m_fCollisionRadius; return *this; } }; VALIDATE_SIZE(CColPoint, 0x28);
Lyuu17/plugin_sdk
plugin_III/game_III/CVehicleModelInfo.h
/* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CClumpModelInfo.h" #include "CVector.h" #include "CRGBA.h" #include "eHandlingIndex.h" #pragma pack(push, 4) class CVehicleModelInfo : public CClumpModelInfo { public: char m_nLastPrimaryColor; char m_nLastSecondaryColor; char m_szGameName[32]; // char _pad56[2]; unsigned int m_nVehicleType; int m_nWheelModelIndex; float m_fWheelScale; unsigned int m_nNumDoors; eHandlingIndex m_nHandlingId; unsigned int m_nVehicleClass; unsigned int m_nLvl; CVector m_avDummyPos[10]; union { unsigned int m_nCompRules; struct { unsigned int nExtraA_comp1 : 4; unsigned int nExtraA_comp2 : 4; unsigned int nExtraA_comp3 : 4; unsigned int nExtraA_rule : 4; unsigned int nExtraB_comp1 : 4; unsigned int nExtraB_comp2 : 4; unsigned int nExtraB_comp3 : 4; unsigned int nExtraB_rule : 4; } m_nCompRulesBits; }; float m_fBikeSteerAngle; // unsued; sets to 999.99 in CModelInfo::AddVehicleModel, but not used then. RpMaterial *m_apMaterialsPrimary[26]; RpMaterial *m_apMaterialsSecondary[26]; unsigned char m_anPrimaryColors[8]; unsigned char m_anSecondaryColors[8]; unsigned char m_nNumColorVariations; unsigned char m_nLastColorVariation; unsigned char m_nCurrentPrimaryColor; unsigned char m_nCurrentSecondaryColor; RwTexture *m_pEnvironmentTex; RpAtomic *m_apExtras[6]; unsigned int m_nNumExtras; //variables static CRGBA *ms_colourTextureTable; static char *ms_compsUsed; // [2] static char *ms_compsToUse; // [2] static RwTexture **ms_pEnvironmentMaps; // array with 1 element static RwObjectNameIdAssocation *ms_vehicleDescs; //funcs void AvoidSameVehicleColour(unsigned char* prim, unsigned char* sec); CVehicleModelInfo(); // get vehicle extra with rules. Returns extra id. void ChooseComponent(); // get vehicle second extra with rules. Returns extra id. void ChooseSecondComponent(); void ChooseVehicleColour(unsigned char& prim, unsigned char& sec); static RwObject* ClearAtomicFlagCB(RwObject* object, void* data); // move all objects from data (it is actually RwFrame *) to frame static RwFrame* CollapseFramesCB(RwFrame* frame, void* data); // do nothing static void DeleteVehicleColourTextures(); int FindEditableMaterialList(); static RpAtomic* GetEditableMaterialListCB(RpAtomic* atomic, void* data); static RpMaterial* GetEditableMaterialListCB(RpMaterial* material, void* data); // gets max number of passengers for model static int GetMaximumNumberOfPassengersFromNumberOfDoors(int modelId); // get wheel position. Wheel is wheel id [0-3]. Local - get local offset (if false it will get world position) void GetWheelPosn(int wheel, CVector& outVec); static RpMaterial* HasAlphaMaterialCB(RpMaterial* material, void* data); static RpMaterial* HasSpecularMaterialCB(RpMaterial* material, void* data); static RpAtomic* HideAllComponentsAtomicCB(RpAtomic* atomic, void* data); static RpAtomic* HideDamagedAtomicCB(RpAtomic* atomic, void* data); // loads 'white' texture static void LoadEnvironmentMaps(); static void LoadVehicleColours(); // set new parent frame for object. Data is actually RwFrame * static RpAtomic* MoveObjectsCB(RwObject* object, void* data); // setup vehicle model components void PreprocessHierarchy(); // setup objects flag. Data is actually flag (unsigned short) static RwObject* SetAtomicFlagCB(RwObject* object, void* data); void SetAtomicRenderCallbacks(); // setup atomic renderer. Data is unused static RpAtomic* SetAtomicRendererCB(RpAtomic* atomic, void* data); // setup BigVehicle renderer. Data is unused static RpAtomic* SetAtomicRendererCB_BigVehicle(RpAtomic* atomic, void* data); // setup boat renderer. Data is unused static RpAtomic* SetAtomicRendererCB_Boat(RpAtomic* atomic, void* data); // setup heli renderer. Data is unused static RpAtomic* SetAtomicRendererCB_Heli(RpAtomic* atomic, void* data); // setup train renderer. Data is unused static RpAtomic* SetAtomicRendererCB_Train(RpAtomic* atomic, void* data); void SetEnvironmentMap(); static RpAtomic* SetEnvironmentMapCB(RpAtomic* atomic, void* data); static RpMaterial* SetEnvironmentMapCB(RpMaterial* material, void* data); // set current vehicle colour for model void SetVehicleColour(unsigned char prim, unsigned char sec); void SetVehicleComponentFlags(RwFrame* component, unsigned int flags); // unloads 'white' texture static void ShutdownEnvironmentMaps(); ~CVehicleModelInfo(); }; #pragma pack(pop) VALIDATE_SIZE(CVehicleModelInfo, 0x1F8); extern RwFrame *&pMatFxIdentityFrame; bool IsValidCompRule(int rule); int GetListOfComponentsNotUsedByRules(unsigned int compRulesBits, int numExtras, int* variationsList); int CountCompsInRule(int compRulesBits); int ChooseComponent(int rule, int compRulesBits); struct VehicleModelStore { unsigned int m_nCount; CVehicleModelInfo m_sObject[120]; ~VehicleModelStore(); };
Lyuu17/plugin_sdk
plugin_III/game_III/meta/meta.CPed.h
/* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "PluginBase.h" namespace plugin { CTOR_META_BEGIN(CPed) static int address; static int global_address; static const int id = 0x43D4F0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4C41C0, 0x43D4F0, 0>; using refs_t = RefList<>; using def_t = CPed(CPed*, int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CPed*, int>, 0, 1>; META_END DTOR_META_BEGIN(CPed) static int address; static int global_address; static const int id = 0x43D4F0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x43D4F0, 0x4C5170, 0>; using refs_t = RefList<>; using def_t = void(CPed*); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CPed*>, 0>; META_END META_BEGIN(CPed::IsPlayer) static int address; static int global_address; static const int id = 0x4D48E0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4D48E0, 0x4D4980, 0x4D4910>; using refs_t = RefList<>; using def_t = bool(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CPed::UseGroundColModel) static int address; static int global_address; static const int id = 0x4CE730; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4CE730, 0x4CE7D0, 0x4CE760>; using refs_t = RefList<>; using def_t = bool(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CPed::AddWeaponModel) static int address; static int global_address; static const int id = 0x4CF8F0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4CF8F0, 0x4CF990, 0>; using refs_t = RefList<>; using def_t = void(int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<int>, 0>; META_END META_BEGIN_OVERLOADED(CPed::SetAimFlag, void(CPed::*)(CEntity*)) static int address; static int global_address; static const int id = 0x4C69E0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4C69E0, 0x4C6A80, 0>; using refs_t = RefList<>; using def_t = void(CEntity*); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CEntity*>, 0>; META_END META_BEGIN_OVERLOADED(CPed::SetAimFlag, void(CPed::*)(float)) static int address; static int global_address; static const int id = 0x4C6960; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4C6960, 0x4C6A00, 0>; using refs_t = RefList<>; using def_t = void(float); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<float>, 0>; META_END META_BEGIN(CPed::SetAttack) static int address; static int global_address; static const int id = 0x4E6220; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4E6220, 0x4E62D0, 0>; using refs_t = RefList<>; using def_t = void(CEntity*); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CEntity*>, 0>; META_END META_BEGIN(CPed::SetAttackTimer) static int address; static int global_address; static const int id = 0x4D1300; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4D1300, 0x4D13A0, 0>; using refs_t = RefList<>; using def_t = void(unsigned int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<unsigned int>, 0>; META_END META_BEGIN(CPed::SetPointGunAt) static int address; static int global_address; static const int id = 0x4E5F70; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4E5F70, 0x4E6020, 0>; using refs_t = RefList<>; using def_t = void(CEntity*); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CEntity*>, 0>; META_END META_BEGIN(CPed::ClearAimFlag) static int address; static int global_address; static const int id = 0x4C6A50; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4C6A50, 0x4C6AF0, 0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CPed::RestorePreviousState) static int address; static int global_address; static const int id = 0x4C5E30; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4C5E30, 0x4C5ED0, 0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CPed::ClearPointGunAt) static int address; static int global_address; static const int id = 0x4E6180; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4E6180, 0x4E6230, 0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CPed::ClearLookFlag) static int address; static int global_address; static const int id = 0x4C64F0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4C64F0, 0x4C6590, 0>; using refs_t = RefList<>; using def_t = char(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CPed::GiveWeapon) static int address; static int global_address; static const int id = 0x4CF9B0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4CF9B0, 0x4CFA50, 0>; using refs_t = RefList<>; using def_t = void(eWeaponType, unsigned int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<eWeaponType, unsigned int>, 0, 1>; META_END META_BEGIN(CPed::SetCurrentWeapon) static int address; static int global_address; static const int id = 0x4CFA60; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4CFA60, 0x4CFB00, 0>; using refs_t = RefList<>; using def_t = void(int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<int>, 0>; META_END META_BEGIN_OVERLOADED(CPed::SetObjective, void(CPed::*)(eObjective)) static int address; static int global_address; static const int id = 0x4D82C0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4D82C0, 0x4D8360, 0>; using refs_t = RefList<>; using def_t = void(eObjective); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<eObjective>, 0>; META_END META_BEGIN_OVERLOADED(CPed::SetObjective, void(CPed::*)(eObjective, CVector const&)) static int address; static int global_address; static const int id = 0x4D8A90; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4D8A90, 0x4D8B30, 0>; using refs_t = RefList<>; using def_t = void(eObjective, CVector const&); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<eObjective, CVector const&>, 0, 1>; META_END META_BEGIN_OVERLOADED(CPed::SetObjective, void(CPed::*)(eObjective, CVector, float)) static int address; static int global_address; static const int id = 0x4D8770; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4D8770, 0x4D8810, 0>; using refs_t = RefList<>; using def_t = void(eObjective, CVector, float); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<eObjective, CVector, float>, 0, 1, 2>; META_END META_BEGIN_OVERLOADED(CPed::SetObjective, void(CPed::*)(eObjective, short, short)) static int address; static int global_address; static const int id = 0x4D89A0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4D89A0, 0x4D8A40, 0>; using refs_t = RefList<>; using def_t = void(eObjective, short, short); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<eObjective, short, short>, 0, 1, 2>; META_END META_BEGIN_OVERLOADED(CPed::SetObjective, void(CPed::*)(eObjective, void*)) static int address; static int global_address; static const int id = 0x4D83E0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4D83E0, 0x4D8480, 0>; using refs_t = RefList<>; using def_t = void(eObjective, void*); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<eObjective, void*>, 0, 1>; META_END META_BEGIN(CPed::SetObjectiveTimer) static int address; static int global_address; static const int id = 0x4D81E0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4D81E0, 0x4D8280, 0>; using refs_t = RefList<>; using def_t = void(unsigned int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<unsigned int>, 0>; META_END META_BEGIN(CPed::WarpPedIntoCar) static int address; static int global_address; static const int id = 0x4D7D20; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4D7D20, 0x4D7DC0, 0>; using refs_t = RefList<>; using def_t = void(CVehicle*); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<CVehicle*>, 0>; META_END META_BEGIN(CPed::RemoveWeaponModel) static int address; static int global_address; static const int id = 0x4CF980; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4CF980, 0x4CFA20, 0>; using refs_t = RefList<>; using def_t = void(int); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<int>, 0>; META_END META_BEGIN(CPed::StopNonPartialAnims) static int address; static int global_address; static const int id = 0x4C5D50; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4C5D50, 0x4C5DF0, 0>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Thiscall; using args_t = ArgPick<ArgTypes<>>; META_END }
Lyuu17/plugin_sdk
plugin_III/game_III/cPoliceRadio.h
/* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CVector.h" struct cAMCrime { int m_CrimeType; CVector m_vecPos; short m_nSampleIndex; char _pad0[2]; }; struct cPoliceRadioQueue { int aSampleIndeces[60]; unsigned char field_F0; unsigned char field_F1; unsigned char nSample; char _pad0[1]; cAMCrime aObjects[10]; };
Lyuu17/plugin_sdk
plugin_III/game_III/meta/meta.CSprite.h
/* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "PluginBase.h" namespace plugin { META_BEGIN(CSprite::CalcScreenCoors) static int address; static int global_address; static const int id = 0x51C3A0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51C3A0, 0x051C5D0, 0x51C560>; using refs_t = RefList<>; using def_t = bool(CVector const&, RwV3d*, float*, float*, bool); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<CVector const&, RwV3d*, float*, float*, bool>, 0, 1, 2, 3, 4>; META_END META_BEGIN(CSprite::CalcHorizonCoors) static int address; static int global_address; static const int id = 0x51C4A0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51C4A0, 0x51C6D0, 0x51C660>; using refs_t = RefList<>; using def_t = double(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CSprite::FlushSpriteBuffer) static int address; static int global_address; static const int id = 0x51C520; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51C520, 0x51C750, 0x51C6E0>; using refs_t = RefList<>; using def_t = int(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CSprite::InitSpriteBuffer) static int address; static int global_address; static const int id = 0x51C590; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51C590, 0x51C7C0, 0x51C750>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CSprite::InitSpriteBuffer2D) static int address; static int global_address; static const int id = 0x51C5B0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51C5B0, 0x51C7E0, 0x51C770>; using refs_t = RefList<>; using def_t = void(); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<>>; META_END META_BEGIN(CSprite::RenderBufferedOneXLUSprite) static int address; static int global_address; static const int id = 0x51C5D0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51C5D0, 0x51C800, 0x51C790>; using refs_t = RefList<>; using def_t = int(float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, unsigned char); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, unsigned char>, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10>; META_END META_BEGIN(CSprite::RenderOneXLUSprite) static int address; static int global_address; static const int id = 0x51C960; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51C960, 0x51CB90, 0x51CB20>; using refs_t = RefList<>; using def_t = int(float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, unsigned char); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, unsigned char>, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10>; META_END META_BEGIN(CSprite::RenderBufferedOneXLUSprite_Rotate_Aspect) static int address; static int global_address; static const int id = 0x51CCD0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51CCD0, 0x51CF00, 0x51CE90>; using refs_t = RefList<>; using def_t = int(float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, unsigned short); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, float, unsigned char>, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11>; META_END META_BEGIN(CSprite::RenderOneXLUSprite_Rotate_Aspect) static int address; static int global_address; static const int id = 0x51D110; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51D110, 0x51D340, 0x51D2D0>; using refs_t = RefList<>; using def_t = short(float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, float, unsigned char); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, float, unsigned char>, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11>; META_END META_BEGIN(CSprite::RenderBufferedOneXLUSprite_Rotate_Dimension) static int address; static int global_address; static const int id = 0x51D5B0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51D5B0, 0x51D7E0, 0x51D770>; using refs_t = RefList<>; using def_t = short(float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, float, unsigned char); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, float, unsigned char>, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11>; META_END META_BEGIN(CSprite::RenderBufferedOneXLUSprite_Rotate_2Colours) static int address; static int global_address; static const int id = 0x51D9E0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51D9E0, 0x51DC10, 0x51DBA0>; using refs_t = RefList<>; using def_t = short(float, float, float, float, float, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, float, float, float, float, unsigned char); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<float, float, float, float, float, unsigned char, unsigned char, unsigned char, short, float, float, unsigned char>, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11>; META_END META_BEGIN(CSprite::RenderBufferedOneXLUSprite2D) static int address; static int global_address; static const int id = 0x51E3C0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51E3C0, 0x51E5F0, 0x51E580>; using refs_t = RefList<>; using def_t = int(float, float, float, float, RwRGBA*, short, char); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<float, float, float, float, RwRGBA*, short, char>, 0, 1, 2, 3, 4, 5, 6>; META_END META_BEGIN(CSprite::RenderBufferedOneXLUSprite2D_Rotate_Dimension) static int address; static int global_address; static const int id = 0x51E490; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51E490, 0x51E6C0, 0x51E650>; using refs_t = RefList<>; using def_t = int(float, float, float, float, RwRGBA*, short, float, char); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<float, float, float, float, RwRGBA*, short, float, char>, 0, 1, 2, 3, 4, 5, 6, 7>; META_END META_BEGIN_OVERLOADED(CSprite::Set6Vertices2D, int(*)(RwD3D8Vertex*, CRect*, unsigned char, unsigned char, unsigned char, unsigned char)) static int address; static int global_address; static const int id = 0x51E5F0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51E5F0, 0x51E820, 0x51E7B0>; using refs_t = RefList<>; using def_t = int(RwD3D8Vertex*, CRect*, unsigned char, unsigned char, unsigned char, unsigned char); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<RwD3D8Vertex*, CRect*, unsigned char, unsigned char, unsigned char, unsigned char>, 0, 1, 2, 3, 4, 5>; META_END META_BEGIN_OVERLOADED(CSprite::Set6Vertices2D, int(*)(RwD3D8Vertex*, float, float, float, float, float, float, float, float, unsigned char*, unsigned char*, unsigned char*, unsigned char*)) static int address; static int global_address; static const int id = 0x51E7F0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x51E7F0, 0x51EA20, 0x51E9B0>; using refs_t = RefList<>; using def_t = int(RwD3D8Vertex*, float, float, float, float, float, float, float, float, unsigned char*, unsigned char*, unsigned char*, unsigned char*); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<RwD3D8Vertex*, float, float, float, float, float, float, float, float, unsigned char*, unsigned char*, unsigned char*, unsigned char*>, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13>; META_END }
Lyuu17/plugin_sdk
plugin_III/game_III/meta/meta.CWorld.h
/* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "PluginBase.h" namespace plugin { META_BEGIN(CWorld::CameraToIgnoreThisObject) static int address; static int global_address; static const int id = 0X4B5C30; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0X4B5C30, 0X4B5D20, 0X4B5CB0>; using refs_t = RefList<>; using def_t = void(CEntity *); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<CEntity *>, 0>; META_END META_BEGIN(CWorld::FindGroundZFor3DCoord) static int address; static int global_address; static const int id = 0x4B3AE0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4B3AE0, 0x4B3BD0, 0x4B3B60>; using refs_t = RefList<>; using def_t = void(float, float, float, bool*); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<float, float, float, bool*>, 0, 1, 2, 3>; META_END META_BEGIN(CWorld::ProcessLineOfSight) static int address; static int global_address; static const int id = 0X4AF970; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4AF970, 0x4AFA60, 0x4AF9F0>; using refs_t = RefList<>; using def_t = void(CVector const&, CVector const&, CColPoint&, CEntity*&, bool, bool, bool, bool, bool, bool, bool); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<CVector const&, CVector const&, CColPoint &, CEntity * &, bool, bool, bool, bool, bool, bool, bool>, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10>; META_END META_BEGIN(CWorld::ProcessVerticalLine) static int address; static int global_address; static const int id = 0x4B0DE0; static const bool is_virtual = false; static const int vtable_index = -1; using mv_addresses_t = MvAddresses<0x4B0DE0, 0x4B0ED0, 0x4B0E60>; using refs_t = RefList<>; using def_t = void(CVector const&, float, CColPoint&, CEntity*&, bool, bool, bool, bool, bool, bool, CStoredCollPoly*); static const int cb_priority = PRIORITY_BEFORE; using calling_convention_t = CallingConventions::Cdecl; using args_t = ArgPick<ArgTypes<CVector const&, float, CColPoint &, CEntity * &, bool, bool, bool, bool, bool, bool, CStoredCollPoly *>, 0, 1, 2, 3, 4, 5, 6, 7, 9, 10>; META_END }
naughtyboypsp/RTLbsLocationSDK
RTLbsLocationSDK/RTLbsLocPoiInfo.h
// // RTLbsLocPoiInfo.h // BeaconLocation // // Created by zhaoyubin on 15/12/24. // Copyright © 2015年 zhaoyubin. All rights reserved. // #import <Foundation/Foundation.h> ///Poi信息类 @interface RTLbsLocPoiInfo : NSObject @property(nonatomic,copy)NSString *build_name; @property(nonatomic,copy)NSString *floor; @property(nonatomic,copy)NSString *poi_name; @property(nonatomic,copy)NSString *poi_id; @property(nonatomic,assign)BOOL is_inside; @end
naughtyboypsp/RTLbsLocationSDK
RTLbsLocationSDK/RTLbsLocationVersion.h
<reponame>naughtyboypsp/RTLbsLocationSDK<gh_stars>0 // // RTLbsLocationVersion.h // BeaconLocation // // Created by zhaoyubin on 15/8/12. // Copyright (c) 2015年 zhaoyubin. All rights reserved. // #import <UIKit/UIKit.h> /*****更新日志:***** SDK V2.0.1 so库 V6.4.1 在线定位数据包添加licenseKey SDK V2.1 so库 V6.4.1 优化定位逻辑 添加设置定位频率的属性 添加手动更新建筑物判断和指纹数据接口 SDK V2.2 so库 V6.4.1 优化定位初始化逻辑,缩短初始化时间 提高定位稳定性 SDK V2.3 so库 V6.4.1 定位出错信息中添加beacon数量、蓝牙及网络状态信息 增加地图约束功能 SDK V2.4 so库 V6.6.3 增加多UUID支持 增加气压测高,提高楼层判断的准确度 SDK V2.4.1 so库 V6.6.3 添加场景API接口 SDK V2.5 so库 V6.7.2 优化PDR推算逻辑,提高定位稳定性 优化beacon加解密算法 *********************/ /** *获取当前定位API的版本号 *return 返回当前API的版本号 */ UIKIT_STATIC_INLINE NSString * RtmapGetLocationApiVersion() { return @"2.5"; }
clayne/c-blosc2
examples/simple.c
/* Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) Example program demonstrating the use of a Blosc from C code. To compile this program: $ gcc -O simple.c -o simple -lblosc2 To run: $ ./simple Blosc version info: 2.0.0a2 ($Date:: 2016-01-08 #$) Compression: 40000000 -> 832774 (48.0x) Correctly extracted 5 elements from compressed chunk! Decompression successful! Successful roundtrip! */ #include <stdio.h> #include "blosc2.h" #define SIZE (10 * 1000 * 1000) #define NTHREADS 2 int main(void) { static float data[SIZE]; static float data_out[SIZE]; static float data_dest[SIZE]; float data_subset[5]; float data_subset_ref[5] = {5, 6, 7, 8, 9}; size_t isize = SIZE * sizeof(float), osize = SIZE * sizeof(float); int dsize = SIZE * sizeof(float), csize; int i, ret; for (i = 0; i < SIZE; i++) { data[i] = (float)i; } printf("Blosc version info: %s (%s)\n", BLOSC_VERSION_STRING, BLOSC_VERSION_DATE); /* Initialize the Blosc compressor */ blosc_init(); blosc_set_nthreads(NTHREADS); /* Compress with clevel=5 and shuffle active */ csize = blosc_compress(5, BLOSC_BITSHUFFLE, sizeof(float), isize, data, data_out, osize); if (csize == 0) { printf("Buffer is uncompressible. Giving up.\n"); return 1; } else if (csize < 0) { printf("Compression error. Error code: %d\n", csize); return csize; } printf("Compression: %zu -> %d (%.1fx)\n", isize, csize, (1. * (double)isize) / csize); ret = blosc_getitem(data_out, 5, 5, data_subset); if (ret < 0) { printf("Error in blosc_getitem(). Giving up.\n"); return 1; } for (i = 0; i < 5; i++) { if (data_subset[i] != data_subset_ref[i]) { printf("blosc_getitem() fetched data differs from original!\n"); return -1; } } printf("Correctly extracted 5 elements from compressed chunk!\n"); /* Decompress */ dsize = blosc_decompress(data_out, data_dest, (size_t)dsize); if (dsize < 0) { printf("Decompression error. Error code: %d\n", dsize); return dsize; } printf("Decompression successful!\n"); /* After using it, destroy the Blosc environment */ blosc_destroy(); for (i = 0; i < SIZE; i++) { if (data[i] != data_dest[i]) { printf("Decompressed data differs from original!\n"); return -1; } } printf("Successful roundtrip!\n"); return 0; }
clayne/c-blosc2
plugins/codecs/zfp/blosc2-zfp.h
/********************************************************************* Blosc - Blocked Shuffling and Compression Library Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ #ifndef BLOSC2_ZFP_H #define BLOSC2_ZFP_H #include "zfp-private.h" #if defined (__cplusplus) extern "C" { #endif int zfp_acc_compress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_cparams *cparams, const void* chunk); int zfp_acc_decompress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_dparams *dparams, const void* chunk); int zfp_prec_compress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_cparams *cparams, const void* chunk); int zfp_prec_decompress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_dparams *dparams, const void* chunk); int zfp_rate_compress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_cparams *cparams, const void* chunk); int zfp_rate_decompress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_dparams *dparams, const void* chunk); int zfp_getcell(blosc2_context *context, const uint8_t *block, int32_t cbytes, uint8_t *dest, int32_t destsize); #if defined (__cplusplus) } #endif #endif /* BLOSC2_ZFP_H */
clayne/c-blosc2
plugins/codecs/ndlz/ndlz4x4.c
/********************************************************************* Blosc - Blocked Shuffling and Compression Library Author: <NAME> <<EMAIL>> Author: <NAME> <<EMAIL>> Author: <NAME> <<EMAIL>> Creation date: 2020-06-12 See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ /********************************************************************* This codec is meant to leverage multidimensionality for getting better compression ratios. The idea is to look for similarities in places that are closer in a euclidean metric, not the typical linear one. **********************************************************************/ #include <stdio.h> #include "ndlz4x4.h" #include "ndlz.h" #include "xxhash.h" #include "../plugins/plugin_utils.h" /* * Give hints to the compiler for branch prediction optimization. */ #if defined(__GNUC__) && (__GNUC__ > 2) #define NDLZ_EXPECT_CONDITIONAL(c) (__builtin_expect((c), 1)) #define NDLZ_UNEXPECT_CONDITIONAL(c) (__builtin_expect((c), 0)) #else #define NDLZ_EXPECT_CONDITIONAL(c) (c) #define NDLZ_UNEXPECT_CONDITIONAL(c) (c) #endif /* * Use inlined functions for supported systems. */ #if defined(_MSC_VER) && !defined(__cplusplus) /* Visual Studio */ #define inline __inline /* Visual C is not C99, but supports some kind of inline */ #endif #define MAX_COPY 32U #define MAX_DISTANCE 65535 #ifdef BLOSC_STRICT_ALIGN #define NDLZ_READU16(p) ((p)[0] | (p)[1]<<8) #define NDLZ_READU32(p) ((p)[0] | (p)[1]<<8 | (p)[2]<<16 | (p)[3]<<24) #else #define NDLZ_READU16(p) *((const uint16_t*)(p)) #define NDLZ_READU32(p) *((const uint32_t*)(p)) #endif #define HASH_LOG (12) int ndlz4_compress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_cparams *cparams) { BLOSC_UNUSED_PARAM(meta); int8_t ndim; int64_t* shape = malloc(8 * sizeof(int64_t)); int32_t* chunkshape = malloc(8 * sizeof(int32_t)); int32_t* blockshape = malloc(8 * sizeof(int32_t)); uint8_t* smeta; int32_t smeta_len; if (blosc2_meta_get(cparams->schunk, "caterva", &smeta, &smeta_len) < 0) { printf("Blosc error"); return -1; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); if (ndim != 2) { fprintf(stderr, "This codec only works for ndim = 2"); return -1; } if (input_len != (blockshape[0] * blockshape[1])) { printf("Length not equal to blocksize \n"); return -1; } if (NDLZ_UNEXPECT_CONDITIONAL(output_len < (int) (1 + ndim * sizeof(int32_t)))) { printf("Output too small \n"); return -1; } uint8_t* ip = (uint8_t *) input; uint8_t* op = (uint8_t *) output; uint8_t* op_limit; uint32_t hval, hash_cell; uint32_t hash_triple[2] = {0}; uint32_t hash_pair[3] = {0}; uint8_t bufarea[16]; uint8_t* buf_cell = bufarea; uint8_t buf_triple[12]; uint8_t buf_pair[8]; uint8_t* buf_aux; uint32_t tab_cell[1U << 12U] = {0}; uint32_t tab_triple[1U << 12U] = {0}; uint32_t tab_pair[1U << 12U] = {0}; uint32_t update_triple[2] = {0}; uint32_t update_pair[3] = {0}; // Minimum cratios before issuing and _early giveup_ // Remind that ndlz is not meant for cratios <= 2 (too costly to decompress) op_limit = op + output_len; // Initialize the hash table to distances of 0 for (unsigned i = 0; i < (1U << 12U); i++) { tab_cell[i] = 0; } /* input and output buffer cannot be less than 16 and 66 bytes or we can get into trouble */ int overhead = 17 + (blockshape[0] * blockshape[1] / 16 - 1) * 2; if (input_len < 16 || output_len < overhead) { printf("Incorrect length or maxout"); return 0; } uint8_t* obase = op; /* we start with literal copy */ *op++ = ndim; memcpy(op, &blockshape[0], 4); op += 4; memcpy(op, &blockshape[1], 4); op += 4; uint32_t i_stop[2]; for (int i = 0; i < 2; ++i) { i_stop[i] = (blockshape[i] + 3) / 4; } /* main loop */ uint32_t padding[2]; uint32_t ii[2]; for (ii[0] = 0; ii[0] < i_stop[0]; ++ii[0]) { for (ii[1] = 0; ii[1] < i_stop[1]; ++ii[1]) { // for each cell uint8_t token; for (int h = 0; h < 2; h++) { // new cell -> new possible references update_triple[h] = 0; update_pair[h] = 0; } update_pair[2] = 0; if (NDLZ_UNEXPECT_CONDITIONAL(op + 16 + 1 > op_limit)) { free(shape); free(chunkshape); free(blockshape); return 0; } uint32_t orig = ii[0] * 4 * blockshape[1] + ii[1] * 4; if (((blockshape[0] % 4 != 0) && (ii[0] == i_stop[0] - 1)) || ((blockshape[1] % 4 != 0) && (ii[1] == i_stop[1] - 1))) { token = 0; // padding -> literal copy *op++ = token; if (ii[0] == i_stop[0] - 1) { padding[0] = (blockshape[0] % 4 == 0) ? 4 : blockshape[0] % 4; } else { padding[0] = 4; } if (ii[1] == i_stop[1] - 1) { padding[1] = (blockshape[1] % 4 == 0) ? 4 : blockshape[1] % 4; } else { padding[1] = 4; } for (uint32_t i = 0; i < padding[0]; i++) { memcpy(op, &ip[orig + i * blockshape[1]], padding[1]); op += padding[1]; } } else { for (uint64_t i = 0; i < 4; i++) { // fill cell buffer uint64_t ind = orig + i * blockshape[1]; memcpy(buf_cell, &ip[ind], 4); buf_cell += 4; } buf_cell -= 16; const uint8_t* ref; uint32_t distance; uint8_t* anchor = op; /* comparison starting-point */ /* find potential match */ hash_cell = XXH32(buf_cell, 16, 1); // calculate cell hash hash_cell >>= 32U - 12U; ref = obase + tab_cell[hash_cell]; /* calculate distance to the match */ if (tab_cell[hash_cell] == 0) { distance = 0; } else { bool same = true; buf_aux = obase + tab_cell[hash_cell]; for(int i = 0; i < 16; i++){ if (buf_cell[i] != buf_aux[i]) { same = false; break; } } if (same) { distance = (int32_t) (anchor - ref); } else { distance = 0; } } bool alleq = true; for (int i = 1; i < 16; i++) { if (buf_cell[i] != buf_cell[0]) { alleq = false; break; } } if (alleq) { // all elements of the cell equal token = (uint8_t) (1U << 6U); *op++ = token; *op++ = buf_cell[0]; } else if (distance == 0 || (distance >= MAX_DISTANCE)) { // no cell match bool literal = true; // 2 rows pairs matches for (int j = 1; j < 4; j++) { memcpy(buf_pair, buf_cell, 4); memcpy(&buf_pair[4], &buf_cell[j * 4], 4); hval = XXH32(buf_pair, 8, 1); // calculate rows pair hash hval >>= 32U - 12U; ref = obase + tab_pair[hval]; /* calculate distance to the match */ bool same = true; uint16_t offset; if (tab_pair[hval] != 0) { buf_aux = obase + tab_pair[hval]; for (int k = 0; k < 8; k++) { if (buf_pair[k] != buf_aux[k]) { same = false; break; } } offset = (uint16_t) (anchor - obase - tab_pair[hval]); } else { same = false; } if (same) { distance = (int32_t) (anchor - ref); } else { distance = 0; } if ((distance != 0) && (distance < MAX_DISTANCE)) { /* rows pair match */ int k, m, l = -1; for (k = 1; k < 4; k++) { if (k != j) { if (l == -1) { l = k; } else { m = k; } } } memcpy(buf_pair, &buf_cell[l * 4], 4); memcpy(&buf_pair[4], &buf_cell[m * 4], 4); hval = XXH32(buf_pair, 8, 1); // calculate rows pair hash hval >>= 32U - 12U; ref = obase + tab_pair[hval]; same = true; if (tab_pair[hval] != 0) { buf_aux = obase + tab_pair[hval]; for (k = 0; k < 8; k++) { if (buf_pair[k] != buf_aux[k]) { same = false; break; } } } else { same = false; } if (same) { distance = (int32_t) (anchor + l * 4 - ref); } else { distance = 0; } if ((distance != 0) && (distance < MAX_DISTANCE)) { /* 2 pair matches */ literal = false; token = (uint8_t) ((1U << 5U) | (j << 3U)); *op++ = token; uint16_t offset_2 = (uint16_t) (anchor - obase - tab_pair[hval]); *(uint16_t *) op = offset; op += sizeof(offset); *(uint16_t *) op = offset_2; op += sizeof(offset_2); goto match; } } } // rows triples for(int i = 0; i < 2; i++) { memcpy(buf_triple, &buf_cell[i * 4], 4); for (int j = i + 1; j < 3; j++) { memcpy(&buf_triple[4], &buf_cell[j * 4], 4); for (int k = j + 1; k < 4; k++) { memcpy(&buf_triple[8], &buf_cell[k * 4], 4); hval = XXH32(buf_triple, 12, 1); // calculate triple hash hval >>= 32U - 12U; /* calculate distance to the match */ bool same = true; uint16_t offset; if (tab_triple[hval] != 0) { buf_aux = obase + tab_triple[hval]; for (int l = 0; l < 12; l++) { if (buf_triple[l] != buf_aux[l]) { same = false; break; } } offset = (uint16_t) (anchor - obase - tab_triple[hval]); } else { same = false; if ((j - i == 1) && (k - j == 1)) { update_triple[i] = (uint32_t) (anchor + 1 + i * 4 - obase); /* update hash table */ hash_triple[i] = hval; } } ref = obase + tab_triple[hval]; if (same) { distance = (int32_t) (anchor + i * 4 - ref); } else { distance = 0; } if ((distance != 0) && (distance < MAX_DISTANCE)) { literal = false; if (i == 1) { token = (uint8_t) (7U << 5U); } else { token = (uint8_t) ((7U << 5U) | ((j + k - 2) << 3U)); } *op++ = token; memcpy(op, &offset, 2); op += 2; for (int l = 0; l < 4; l++) { if ((l != i) && (l != j) && (l != k)) { memcpy(op, &buf_cell[4 * l], 4); op += 4; goto match; } } } } } } // rows pairs for(int i = 0; i < 3; i++) { memcpy(buf_pair, &buf_cell[i * 4], 4); for (int j = i + 1; j < 4; j++) { memcpy(&buf_pair[4], &buf_cell[j * 4], 4); hval = XXH32(buf_pair, 8, 1); // calculate rows pair hash hval >>= 32U - 12U; ref = obase + tab_pair[hval]; /* calculate distance to the match */ bool same = true; uint16_t offset; if (tab_pair[hval] != 0) { buf_aux = obase + tab_pair[hval]; for(int k = 0; k < 8; k++){ if(buf_pair[k] != buf_aux[k]) { same = false; break; } } offset = (uint16_t) (anchor - obase - tab_pair[hval]); } else { same = false; if (j - i == 1) { update_pair[i] = (uint32_t) (anchor + 1 + i * 4 - obase); /* update hash table */ hash_pair[i] = hval; } } if (same) { distance = (int32_t) (anchor + i * 4 - ref); } else { distance = 0; } if ((distance != 0) && (distance < MAX_DISTANCE)) { /* rows pair match */ literal = false; if (i == 2) { token = (uint8_t) (1U << 7U); } else { token = (uint8_t) ((1U << 7U) | (i << 5U) | (j << 3U)); } *op++ = token; memcpy(op, &offset, 2); op += 2; for (int k = 0; k < 4; k++) { if ((k != i) && (k != j)) { memcpy(op, &buf_cell[4 * k], 4); op += 4; } } goto match; } } } match: if (literal) { tab_cell[hash_cell] = (uint32_t) (anchor + 1 - obase); /* update hash tables */ if (update_triple[0] != 0) { for (int h = 0; h < 2; h++) { tab_triple[hash_triple[h]] = update_triple[h]; } } if (update_pair[0] != 0) { for (int h = 0; h < 3; h++) { tab_pair[hash_pair[h]] = update_pair[h]; } } token = 0; *op++ = token; memcpy(op, buf_cell, 16); op += 16; } } else { // cell match token = (uint8_t )((<KEY> | (<KEY>)); *op++ = token; uint16_t offset = (uint16_t) (anchor - obase - tab_cell[hash_cell]); memcpy(op, &offset, 2); op += 2; } } if((op - obase) > input_len) { printf("Compressed data is bigger than input! \n"); return 0; } } } free(shape); free(chunkshape); free(blockshape); return (int)(op - obase); } // See https://habr.com/en/company/yandex/blog/457612/ #ifdef __AVX2__ #if defined(_MSC_VER) #define ALIGNED_(x) __declspec(align(x)) #else #if defined(__GNUC__) #define ALIGNED_(x) __attribute__ ((aligned(x))) #endif #endif #define ALIGNED_TYPE_(t, x) t ALIGNED_(x) static unsigned char* copy_match_16(unsigned char *op, const unsigned char *match, int32_t len) { size_t offset = op - match; while (len >= 16) { static const ALIGNED_TYPE_(uint8_t, 16) masks[] = { 0, 1, 2, 1, 4, 1, 4, 2, 8, 7, 6, 5, 4, 3, 2, 1, // offset = 0, not used as mask, but for shift 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // offset = 1 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // offset = 16 }; _mm_storeu_si128((__m128i *)(op), _mm_shuffle_epi8(_mm_loadu_si128((const __m128i *)(match)), _mm_load_si128((const __m128i *)(masks) + offset))); match += masks[offset]; op += 16; len -= 16; } // Deal with remainders for (; len > 0; len--) { *op++ = *match++; } return op; } #endif int ndlz4_decompress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_dparams *dparams) { BLOSC_UNUSED_PARAM(meta); BLOSC_UNUSED_PARAM(dparams); uint8_t* ip = (uint8_t*)input; uint8_t* ip_limit = ip + input_len; uint8_t* op = (uint8_t*)output; uint8_t ndim; uint32_t blockshape[2]; uint32_t eshape[2]; uint8_t* buffercpy; uint8_t local_buffer[16]; uint8_t token; if (NDLZ_UNEXPECT_CONDITIONAL(input_len < 8)) { return 0; } /* we start with literal copy */ ndim = *ip; ip ++; if (ndim != 2) { fprintf(stderr, "This codec only works for ndim = 2"); return -1; } memcpy(&blockshape[0], ip, 4); ip += 4; memcpy(&blockshape[1], ip, 4); ip += 4; eshape[0] = ((blockshape[0] + 3) / 4) * 4; eshape[1] = ((blockshape[1] + 3) / 4) * 4; if (NDLZ_UNEXPECT_CONDITIONAL(output_len < blockshape[0] * blockshape[1])) { return 0; } memset(op, 0, blockshape[0] * blockshape[1]); uint32_t i_stop[2]; for (int i = 0; i < 2; ++i) { i_stop[i] = eshape[i] / 4; } /* main loop */ uint32_t ii[2]; uint32_t padding[2]; uint32_t ind; uint8_t cell_aux[16]; for (ii[0] = 0; ii[0] < i_stop[0]; ++ii[0]) { for (ii[1] = 0; ii[1] < i_stop[1]; ++ii[1]) { // for each cell if (NDLZ_UNEXPECT_CONDITIONAL(ip > ip_limit)) { printf("Literal copy \n"); return 0; } if (ii[0] == i_stop[0] - 1) { padding[0] = (blockshape[0] % 4 == 0) ? 4 : blockshape[0] % 4; } else { padding[0] = 4; } if (ii[1] == i_stop[1] - 1) { padding[1] = (blockshape[1] % 4 == 0) ? 4 : blockshape[1] % 4; } else { padding[1] = 4; } token = *ip++; if (token == 0){ // no match buffercpy = ip; ip += padding[0] * padding[1]; } else if (token == (uint8_t)((1U << 7U) | (1U << 6U))) { // cell match uint16_t offset = *((uint16_t*) ip); buffercpy = ip - offset - 1; ip += 2; } else if (token == (uint8_t)(1U << 6U)) { // whole cell of same element buffercpy = cell_aux; memset(buffercpy, *ip, 16); ip++; } else if (token >= 224) { // three rows match buffercpy = local_buffer; uint16_t offset = *((uint16_t*) ip); offset += 3; ip += 2; int i, j, k; if ((token >> 3U) == 28) { i = 1; j = 2; k = 3; } else { i = 0; if ((token >> 3U) < 30) { j = 1; k = 2; } else { k = 3; if ((token >> 3U) == 30) { j = 1; } else { j = 2; } } } memcpy(&buffercpy[i * 4], ip - offset, 4); memcpy(&buffercpy[j * 4], ip - offset + 4, 4); memcpy(&buffercpy[k * 4], ip - offset + 8, 4); for (int l = 0; l < 4; l++) { if ((l != i) && (l != j) && (l != k)) { memcpy(&buffercpy[l * 4], ip, 4); ip += 4; break; } } } else if ((token >= 128) && (token <= 191)){ // rows pair match buffercpy = local_buffer; uint16_t offset = *((uint16_t*) ip); offset += 3; ip += 2; int i, j; if (token == 128) { i = 2; j = 3; } else { i = (token - 128) >> 5U; j = ((token - 128) >> 3U) - (i << 2U); } memcpy(&buffercpy[i * 4], ip - offset, 4); memcpy(&buffercpy[j * 4], ip - offset + 4, 4); for (int k = 0; k < 4; k++) { if ((k != i) && (k != j)) { memcpy(&buffercpy[k * 4], ip, 4); ip += 4; } } } else if ((token >= 40) && (token <= 63)) { // 2 rows pair matches buffercpy = local_buffer; uint16_t offset_1 = *((uint16_t*) ip); offset_1 += 5; ip += 2; uint16_t offset_2 = *((uint16_t*) ip); offset_2 += 5; ip += 2; int i, j, k, l, m; i = 0; j = ((token - 32) >> 3U); l = -1; for (k = 1; k < 4; k++) { if ((k != i) && (k != j)) { if (l == -1) { l = k; } else { m = k; } } } memcpy(&buffercpy[i * 4], ip - offset_1, 4); memcpy(&buffercpy[j * 4], ip - offset_1 + 4, 4); memcpy(&buffercpy[l * 4], ip - offset_2, 4); memcpy(&buffercpy[m * 4], ip - offset_2 + 4, 4); } else { printf("Invalid token: %u at cell [%d, %d]\n", token, ii[0], ii[1]); return 0; } // fill op with buffercpy uint32_t orig = ii[0] * 4 * blockshape[1] + ii[1] * 4; for (uint32_t i = 0; i < 4; i++) { if (i < padding[0]) { ind = orig + i * blockshape[1]; memcpy(&op[ind], buffercpy, padding[1]); } buffercpy += padding[1]; } if (ind > (uint32_t) output_len) { printf("Output size is bigger than max \n"); return 0; } } } ind += padding[1]; if (ind != (blockshape[0] * blockshape[1])) { printf("Output size is not compatible with embedded blockshape \n"); return 0; } if (ind > (uint32_t) output_len) { printf("Output size is bigger than max \n"); return 0; } return (int)ind; }
clayne/c-blosc2
plugins/filters/ndcell/ndcell.c
<filename>plugins/filters/ndcell/ndcell.c /* Copyright (C) 2021 The Blosc Developers http://blosc.org License: BSD 3-Clause (see LICENSE.txt) */ #include <blosc2.h> #include "ndcell.h" #include <math.h> #include <stdio.h> #include "../plugins/plugin_utils.h" static void index_unidim_to_multidim(int ndim, const int64_t *shape, int64_t i, int64_t *index) { int64_t strides[8]; strides[ndim - 1] = 1; for (int j = ndim - 2; j >= 0; --j) { strides[j] = shape[j + 1] * strides[j + 1]; } index[0] = i / strides[0]; for (int j = 1; j < ndim; ++j) { index[j] = (i % strides[j - 1]) / strides[j]; } } int ndcell_encoder(const uint8_t* input, uint8_t* output, int32_t length, uint8_t meta, blosc2_cparams* cparams) { int8_t ndim; int64_t* shape = malloc(8 * sizeof(int64_t)); int32_t* chunkshape = malloc(8 * sizeof(int32_t)); int32_t* blockshape = malloc(8 * sizeof(int32_t)); uint8_t* smeta; int32_t smeta_len; if (blosc2_meta_get(cparams->schunk, "caterva", &smeta, &smeta_len) < 0) { free(shape); free(chunkshape); free(blockshape); printf("Blosc error"); return 0; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); int typesize = cparams->typesize; int8_t cell_shape = (int8_t)meta; const int cell_size = (int) pow(cell_shape, ndim); int32_t blocksize = (int32_t) typesize; for (int i = 0; i < ndim; i++){ blocksize *= blockshape[i]; } if (length != blocksize) { free(shape); free(chunkshape); free(blockshape); printf("Length not equal to blocksize %d %d \n", length, blocksize); return -1; } uint8_t* ip = (uint8_t *) input; uint8_t* op = (uint8_t *) output; uint8_t* op_limit = op + length; /* input and output buffer cannot be less than cell size */ if (length < cell_size * typesize) { free(shape); free(chunkshape); free(blockshape); printf("Incorrect length"); return 0; } uint8_t* obase = op; int64_t i_shape[NDCELL_MAX_DIM]; for (int i = 0; i < ndim; ++i) { i_shape[i] = (blockshape[i] + cell_shape - 1) / cell_shape; } int64_t ncells = 1; for (int i = 0; i < ndim; ++i) { ncells *= i_shape[i]; } /* main loop */ int64_t pad_shape[NDCELL_MAX_DIM]; int64_t ii[NDCELL_MAX_DIM]; for (int cell_ind = 0; cell_ind < ncells; cell_ind++) { // for each cell index_unidim_to_multidim(ndim, i_shape, cell_ind, ii); uint32_t orig = 0; int64_t nd_aux = (int64_t) cell_shape; for (int i = ndim - 1; i >= 0; i--) { orig += ii[i] * nd_aux; nd_aux *= blockshape[i]; } for (int dim_ind = 0; dim_ind < ndim; dim_ind++) { if ((blockshape[dim_ind] % cell_shape != 0) && (ii[dim_ind] == i_shape[dim_ind] - 1)) { pad_shape[dim_ind] = blockshape[dim_ind] % cell_shape; } else { pad_shape[dim_ind] = (int64_t) cell_shape; } } int64_t ncopies = 1; for (int i = 0; i < ndim - 1; ++i) { ncopies *= pad_shape[i]; } int64_t kk[NDCELL_MAX_DIM]; for (int copy_ind = 0; copy_ind < ncopies; ++copy_ind) { index_unidim_to_multidim(ndim - 1, pad_shape, copy_ind, kk); nd_aux = blockshape[ndim - 1]; int64_t ind = orig; for (int i = ndim - 2; i >= 0; i--) { ind += kk[i] * nd_aux; nd_aux *= blockshape[i]; } memcpy(op, &ip[ind * typesize], pad_shape[ndim - 1] * typesize); op += pad_shape[ndim - 1] * typesize; } if (op > op_limit) { free(shape); free(chunkshape); free(blockshape); printf("Output too big"); return 0; } } if((op - obase) != length) { free(shape); free(chunkshape); free(blockshape); printf("Output size must be equal to input size \n"); return 0; } free(shape); free(chunkshape); free(blockshape); return BLOSC2_ERROR_SUCCESS; } int ndcell_decoder(const uint8_t* input, uint8_t* output, int32_t length, uint8_t meta, blosc2_dparams* dparams) { blosc2_schunk *schunk = dparams->schunk; int8_t ndim; int64_t* shape = malloc(8 * sizeof(int64_t)); int32_t* chunkshape = malloc(8 * sizeof(int32_t)); int32_t* blockshape = malloc(8 * sizeof(int32_t)); uint8_t* smeta; int32_t smeta_len; if (blosc2_meta_get(schunk, "caterva", &smeta, &smeta_len) < 0) { free(shape); free(chunkshape); free(blockshape); printf("Blosc error"); return 0; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); int8_t cell_shape = (int8_t)meta; int cell_size = (int) pow(cell_shape, ndim); int32_t typesize = schunk->typesize; uint8_t* ip = (uint8_t*)input; uint8_t* ip_limit = ip + length; uint8_t* op = (uint8_t*)output; int32_t blocksize = (int32_t) typesize; for (int i = 0; i < ndim; i++){ blocksize *= blockshape[i]; } if (length != blocksize) { free(shape); free(chunkshape); free(blockshape); printf("Length not equal to blocksize \n"); return -1; } /* input and output buffer cannot be less than cell size */ if (length < cell_size * typesize) { free(shape); free(chunkshape); free(blockshape); printf("Incorrect length"); return 0; } int64_t i_shape[NDCELL_MAX_DIM]; for (int i = 0; i < ndim; ++i) { i_shape[i] = (blockshape[i] + cell_shape - 1) / cell_shape; } int64_t ncells = 1; for (int i = 0; i < ndim; ++i) { ncells *= i_shape[i]; } /* main loop */ int64_t pad_shape[NDCELL_MAX_DIM]; int64_t ii[NDCELL_MAX_DIM]; int32_t ind; for (int cell_ind = 0; cell_ind < ncells; cell_ind++) { // for each cell if (ip > ip_limit) { free(shape); free(chunkshape); free(blockshape); printf("Literal copy \n"); return 0; } index_unidim_to_multidim(ndim, i_shape, cell_ind, ii); uint32_t orig = 0; int64_t nd_aux = (int64_t) cell_shape; for (int i = ndim - 1; i >= 0; i--) { orig += ii[i] * nd_aux; nd_aux *= blockshape[i]; } for (int dim_ind = 0; dim_ind < ndim; dim_ind++) { if ((blockshape[dim_ind] % cell_shape != 0) && (ii[dim_ind] == i_shape[dim_ind] - 1)) { pad_shape[dim_ind] = blockshape[dim_ind] % cell_shape; } else { pad_shape[dim_ind] = (int64_t) cell_shape; } } int64_t ncopies = 1; for (int i = 0; i < ndim - 1; ++i) { ncopies *= pad_shape[i]; } int64_t kk[NDCELL_MAX_DIM]; for (int copy_ind = 0; copy_ind < ncopies; ++copy_ind) { index_unidim_to_multidim(ndim - 1, pad_shape, copy_ind, kk); nd_aux = blockshape[ndim - 1]; ind = (int32_t) orig; for (int i = ndim - 2; i >= 0; i--) { ind += (int32_t) (kk[i] * nd_aux); nd_aux *= blockshape[i]; } memcpy(&op[ind * typesize], ip, pad_shape[ndim - 1] * typesize); ip += pad_shape[ndim - 1] * typesize; } } ind += (int32_t) pad_shape[ndim - 1]; if (ind != (int32_t) (blocksize / typesize)) { free(shape); free(chunkshape); free(blockshape); printf("Output size is not compatible with embedded blockshape ind %d %d \n", ind, (blocksize / typesize)); return 0; } free(shape); free(chunkshape); free(blockshape); return BLOSC2_ERROR_SUCCESS; }
clayne/c-blosc2
examples/find_roots.c
/* Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) Example program demonstrating how the different compression params affects the performance of root finding. To compile this program: $ gcc -O3 find_roots.c -o find_roots -lblosc2 To run: $ ./find_roots Blosc version info: 2.0.0a6.dev ($Date:: 2018-05-18 #$) Creation time for X values: 0.178 s, 4274.5 MB/s Compression for X values: 762.9 MB -> 27.3 MB (28.0x) Computing Y polynomial: 0.342 s, 4463.3 MB/s Compression for Y values: 762.9 MB -> 54.0 MB (14.1x) Roots found at: 1.350000023841858, 4.450000286102295, 8.500000953674316, Find root time: 0.401 s, 3806.8 MB/s */ #include <stdio.h> #include "blosc2.h" #define KB 1024. #define MB (1024*KB) #define GB (1024*MB) #define NCHUNKS 500 #define CHUNKSIZE (200 * 1000) // fits well in modern L3 caches #define NTHREADS 4 void fill_buffer(double *x, int nchunk) { double incx = 10. / (NCHUNKS * CHUNKSIZE); for (int i = 0; i < CHUNKSIZE; i++) { x[i] = incx * (nchunk * CHUNKSIZE + i); } } void process_data(const double *x, double *y) { for (int i = 0; i < CHUNKSIZE; i++) { double xi = x[i]; //y[i] = ((.25 * xi + .75) * xi - 1.5) * xi - 2; y[i] = (xi - 1.35) * (xi - 4.45) * (xi - 8.5); } } void find_root(const double *x, const double *y, const double prev_value) { double pv = prev_value; int last_root_idx = -1; for (int i = 0; i < CHUNKSIZE; i++) { double yi = y[i]; if (((yi > 0) - (yi < 0)) != ((pv > 0) - (pv < 0))) { if (last_root_idx != (i - 1)) { printf("%.16g, ", x[i]); last_root_idx = i; // avoid the last point (ULP effects) } } pv = yi; } } int compute_vectors(void) { static double buffer_x[CHUNKSIZE]; static double buffer_y[CHUNKSIZE]; const int32_t isize = CHUNKSIZE * sizeof(double); int dsize; long nbytes = 0; blosc2_schunk *sc_x, *sc_y; int nchunk; blosc_timestamp_t last, current; double ttotal; double prev_value; /* Create a super-chunk container for input (X values) */ blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.typesize = sizeof(double); cparams.compcode = BLOSC_LZ4; cparams.clevel = 9; cparams.filters[0] = BLOSC_TRUNC_PREC; cparams.filters_meta[0] = 23; // treat doubles as floats cparams.nthreads = NTHREADS; blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS; dparams.nthreads = NTHREADS; blosc2_storage storage = {.cparams=&cparams, .dparams=&dparams}; sc_x = blosc2_schunk_new(&storage); /* Create a super-chunk container for output (Y values) */ sc_y = blosc2_schunk_new(&storage); /* Now fill the buffer with even values between 0 and 10 */ blosc_set_timestamp(&last); for (nchunk = 0; nchunk < NCHUNKS; nchunk++) { fill_buffer(buffer_x, nchunk); blosc2_schunk_append_buffer(sc_x, buffer_x, isize); nbytes += (long) isize; } blosc_set_timestamp(&current); ttotal = blosc_elapsed_secs(last, current); printf("Creation time for X values: %.3g s, %.1f MB/s\n", ttotal, (double) nbytes / (ttotal * MB)); printf("Compression for X values: %.1f MB -> %.1f MB (%.1fx)\n", (double)sc_x->nbytes / MB, (double)sc_x->cbytes / MB, (1. * (double)sc_x->nbytes) / (double)sc_x->cbytes); /* Retrieve the chunks and compute the polynomial in another super-chunk */ blosc_set_timestamp(&last); for (nchunk = 0; nchunk < NCHUNKS; nchunk++) { dsize = blosc2_schunk_decompress_chunk(sc_x, nchunk, buffer_x, isize); if (dsize < 0) { printf("Decompression error. Error code: %d\n", dsize); return dsize; } process_data(buffer_x, buffer_y); blosc2_schunk_append_buffer(sc_y, buffer_y, isize); } blosc_set_timestamp(&current); ttotal = blosc_elapsed_secs(last, current); printf("Computing Y polynomial: %.3g s, %.1f MB/s\n", ttotal, 2. * (double) nbytes / (ttotal * MB)); // 2 super-chunks involved printf("Compression for Y values: %.1f MB -> %.1f MB (%.1fx)\n", (double)sc_y->nbytes / MB, (double)sc_y->cbytes / MB, (1. * (double)sc_y->nbytes) / (double)sc_y->cbytes); /* Find the roots of the polynomial */ printf("Roots found at: "); blosc_set_timestamp(&last); prev_value = buffer_y[0]; for (nchunk = 0; nchunk < NCHUNKS; nchunk++) { dsize = blosc2_schunk_decompress_chunk(sc_y, nchunk, (void *) buffer_y, isize); if (dsize < 0) { printf("Decompression error. Error code: %d\n", dsize); return dsize; } dsize = blosc2_schunk_decompress_chunk(sc_x, nchunk, (void *) buffer_x, isize); if (dsize < 0) { printf("Decompression error. Error code: %d\n", dsize); return dsize; } find_root(buffer_x, buffer_y, prev_value); prev_value = buffer_y[CHUNKSIZE - 1]; } blosc_set_timestamp(&current); ttotal = blosc_elapsed_secs(last, current); printf("\n"); printf("Find root time: %.3g s, %.1f MB/s\n", ttotal, 2. * (double) nbytes / (ttotal * MB)); // 2 super-chunks involved /* Free resources */ /* Destroy the super-chunk */ blosc2_schunk_free(sc_x); blosc2_schunk_free(sc_y); return 0; } int main(void) { printf("Blosc version info: %s (%s)\n", BLOSC_VERSION_STRING, BLOSC_VERSION_DATE); /* Initialize the Blosc compressor */ blosc_init(); compute_vectors(); /* Destroy the Blosc environment */ blosc_destroy(); return 0; }
clayne/c-blosc2
plugins/codecs/zfp/zfp-private.h
/********************************************************************* Blosc - Blocked Shuffling and Compression Library Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ #ifndef ZFP_PRIVATE_H #define ZFP_PRIVATE_H #define ZFP_MAX_DIM 4 #define ZFP_CELL_SHAPE 4 #if defined (__cplusplus) extern "C" { #endif #define XXH_INLINE_ALL #define ZFP_ERROR_NULL(pointer) \ do { \ if ((pointer) == NULL) { \ return 0; \ } \ } while (0) static void index_unidim_to_multidim(uint8_t ndim, int32_t *shape, int64_t i, int64_t *index) { int64_t strides[ZFP_MAX_DIM]; strides[ndim - 1] = 1; for (int j = ndim - 2; j >= 0; --j) { strides[j] = shape[j + 1] * strides[j + 1]; } index[0] = i / strides[0]; for (int j = 1; j < ndim; ++j) { index[j] = (i % strides[j - 1]) / strides[j]; } } #if defined (__cplusplus) } #endif #endif /* ZFP_PRIVATE_H */
clayne/c-blosc2
bench/b2bench.c
/********************************************************************* Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) Small benchmark for testing basic capabilities of Blosc. You can select different degrees of 'randomness' in input buffer, as well as external datafiles (uncomment the lines after "For data coming from a file" comment). For usage instructions of this benchmark, please see: https://www.blosc.org/pages/synthetic-benchmarks/ I'm collecting speeds for different machines, so the output of your benchmarks and your processor specifications are welcome! Note: Compiling this with VS2008 does not work well with cmake. Here it is a way to compile the benchmark (with added support for LZ4): > cl /arch:SSE2 /Ox /Febench.exe /Iblosc /Iinternal-complibs\lz4-1.7.0 bench\bench.c blosc\blosc.c blosc\blosclz.c blosc\shuffle.c blosc\shuffle-sse2.c blosc\shuffle-generic.c blosc\bitshuffle-generic.c blosc\bitshuffle-sse2.c internal-complibs\lz4-1.7.0\*.c See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include "blosc2.h" #define KB 1024u #define MB (1024*KB) #define GB (1024*MB) #define NCHUNKS (32*1024) /* maximum number of chunks */ int nchunks = NCHUNKS; int niter = 1; int niter_c = 1; int niter_d = 1; /* default number of iterations */ double totalsize = 0.; /* total compressed/decompressed size */ /* Define posix_memalign for Windows */ #if defined(_WIN32) #include <malloc.h> int posix_memalign(void **memptr, size_t alignment, size_t size) { *memptr = _aligned_malloc(size, alignment); return 0; } /* Buffers allocated with _aligned_malloc need to be freed with _aligned_free. */ #define aligned_free(memptr) _aligned_free(memptr) #else /* If not using MSVC, aligned memory can be freed in the usual way. */ #define aligned_free(memptr) free(memptr) #endif /* defined(_WIN32) && !defined(__MINGW32__) */ /* Given two timeval stamps, return the time per chunk in usec */ double get_usec_chunk(blosc_timestamp_t last, blosc_timestamp_t current, int niter_, int nchunks_) { double elapsed_usecs = 1e-3 * blosc_elapsed_nsecs(last, current); return elapsed_usecs / (double)(niter_ * nchunks_); } int get_value(int i, int rshift) { int v; v = (i << 26) ^ (i << 18) ^ (i << 11) ^ (i << 3) ^ i; if (rshift < 32) { v &= (1 << rshift) - 1; } return v; } void init_buffer(void* src, size_t size, int rshift) { int i; int* _src = (int*)src; /* To have reproducible results */ srand(1); /* Initialize the original buffer */ for (i = 0; i < (int) (size / sizeof(int)); ++i) { /* Choose one below */ /* _src[i] = 0; * _src[i] = 0x01010101; * _src[i] = 0x01020304; * _src[i] = i * 1/.3; * _src[i] = i; */ //_src[i] = rand() >> (32 - rshift); _src[i] = get_value(i, rshift); } } void do_bench(char* compressor, char* shuffle, int nthreads, int size_, int elsize, int rshift, FILE* ofile) { size_t size = (size_t)size_; void* src, *srccpy; void* dest[NCHUNKS], *dest2; int nbytes = 0, cbytes = 0; int i, j, retcode; unsigned char* orig, * round; blosc_timestamp_t last, current; double tmemcpy, tshuf, tunshuf; int clevel, doshuffle = BLOSC_NOFILTER; if (strcmp(shuffle, "shuffle") == 0) { doshuffle = BLOSC_SHUFFLE; } else if (strcmp(shuffle, "bitshuffle") == 0) { doshuffle = BLOSC_BITSHUFFLE; } else if (strcmp(shuffle, "noshuffle") == 0) { doshuffle = BLOSC_NOSHUFFLE; } blosc_set_nthreads((int16_t)nthreads); if (blosc_set_compressor(compressor) < 0) { printf("Compiled w/o support for compressor: '%s', so sorry.\n", compressor); exit(1); } /* Initialize buffers */ srccpy = malloc(size); retcode = posix_memalign(&src, 32, size); if (retcode != 0) { printf("Error in allocating memory!"); } retcode = posix_memalign(&dest2, 32, size); if (retcode != 0) { printf("Error in allocating memory!"); } /* zero src to initialize all bytes on it, and not only multiples of 4 */ memset(src, 0, size); init_buffer(src, size, rshift); memcpy(srccpy, src, size); for (j = 0; j < nchunks; j++) { retcode = posix_memalign(&dest[j], 32, size + BLOSC_MAX_OVERHEAD); if (retcode != 0) { printf("Error in allocating memory!"); } } memset(dest2, 0, size); // just to avoid some GCC compiler warnings fprintf(ofile, "--> %d, %d, %d, %d, %s, %s\n", nthreads, (int)size, elsize, rshift, compressor, shuffle); fprintf(ofile, "********************** Run info ******************************\n"); fprintf(ofile, "Blosc version: %s (%s)\n", BLOSC_VERSION_STRING, BLOSC_VERSION_DATE); fprintf(ofile, "Using synthetic data with %d significant bits (out of 32)\n", rshift); fprintf(ofile, "Dataset size: %d bytes\tType size: %d bytes\n", (int)size, elsize); fprintf(ofile, "Working set: %.1f MB\t\t", (float)(size * nchunks) / (float)MB); fprintf(ofile, "Number of threads: %d\n", nthreads); fprintf(ofile, "********************** Running benchmarks *********************\n"); blosc_set_timestamp(&last); for (i = 0; i < niter; i++) { for (j = 0; j < nchunks; j++) { memcpy(dest[j], src, size); } } blosc_set_timestamp(&current); tmemcpy = get_usec_chunk(last, current, niter, nchunks); fprintf(ofile, "memcpy(write):\t\t %6.1f us, %.1f MB/s\n", tmemcpy, ((float)size * 1e6) / (tmemcpy * MB)); blosc_set_timestamp(&last); for (i = 0; i < niter; i++) { for (j = 0; j < nchunks; j++) { memcpy(dest2, dest[j], size); } } blosc_set_timestamp(&current); tmemcpy = get_usec_chunk(last, current, niter, nchunks); fprintf(ofile, "memcpy(read):\t\t %6.1f us, %.1f MB/s\n", tmemcpy, ((float)size * 1e6) / (tmemcpy * MB)); for (clevel = 0; clevel < 10; clevel++) { fprintf(ofile, "Compression level: %d\n", clevel); blosc_set_timestamp(&last); for (i = 0; i < niter_c; i++) { for (j = 0; j < nchunks; j++) { cbytes = blosc_compress(clevel, doshuffle, (size_t)elsize, size, src, dest[j], size + BLOSC_MAX_OVERHEAD); } } blosc_set_timestamp(&current); tshuf = get_usec_chunk(last, current, niter_c, nchunks); fprintf(ofile, "comp(write):\t %6.1f us, %.1f MB/s\t ", tshuf, ((float)size * 1e6) / (tshuf * MB)); fprintf(ofile, "Final bytes: %d ", cbytes); if (cbytes > 0) { fprintf(ofile, "Ratio: %3.2f", (float)size / (float)cbytes); } fprintf(ofile, "\n"); /* Compressor was unable to compress. Copy the buffer manually. */ if (cbytes == 0) { for (j = 0; j < nchunks; j++) { memcpy(dest[j], src, size); } } blosc_set_timestamp(&last); for (i = 0; i < niter_d; i++) { for (j = 0; j < nchunks; j++) { if (cbytes == 0) { memcpy(dest2, dest[j], size); nbytes = (int)size; } else { nbytes = blosc_decompress(dest[j], dest2, size); } } } blosc_set_timestamp(&current); tunshuf = get_usec_chunk(last, current, niter_d, nchunks); fprintf(ofile, "decomp(read):\t %6.1f us, %.1f MB/s\t ", tunshuf, (nbytes * 1e6) / (tunshuf * MB)); if (nbytes < 0) { fprintf(ofile, "FAILED. Error code: %d\n", nbytes); } /* fprintf(ofile, "Orig bytes: %d\tFinal bytes: %d\n", cbytes, nbytes); */ /* Check if data has had a good roundtrip. Byte-by-byte comparison is slow, so use 'memcmp' to check whether the roundtripped data is correct. If not, fall back to the slow path to print diagnostic messages. */ orig = (unsigned char*)srccpy; round = (unsigned char*)dest2; if (memcmp(orig, round, size) != 0) { for (i = 0; i < (int)size; ++i) { if (orig[i] != round[i]) { fprintf(ofile, "\nError: Original data and round-trip do not match in pos %d\n", i); fprintf(ofile, "Orig--> %x, round-trip--> %x\n", orig[i], round[i]); break; } } } else { i = (int)size; } if (i == (int)size) fprintf(ofile, "OK\n"); } /* End clevel loop */ /* To compute the totalsize, we should take into account the 10 compression levels */ totalsize += ((double)size * nchunks * niter * 10.); aligned_free(src); free(srccpy); aligned_free(dest2); for (i = 0; i < nchunks; i++) { aligned_free(dest[i]); } } /* Compute a sensible value for nchunks */ int get_nchunks(int size_, int ws) { int nchunks_; nchunks_ = ws / size_; if (nchunks_ > NCHUNKS) nchunks_ = NCHUNKS; if (nchunks_ < 1) nchunks_ = 1; return nchunks_; } void print_compress_info(void) { char* name = NULL, * version = NULL; int ret; printf("Blosc version: %s (%s)\n", BLOSC_VERSION_STRING, BLOSC_VERSION_DATE); printf("List of supported compressors in this build: %s\n", blosc_list_compressors()); printf("Supported compression libraries:\n"); ret = blosc_get_complib_info("blosclz", &name, &version); if (ret >= 0) printf(" %s: %s\n", name, version); free(name); free(version); ret = blosc_get_complib_info("lz4", &name, &version); if (ret >= 0) printf(" %s: %s\n", name, version); free(name); free(version); ret = blosc_get_complib_info("zlib", &name, &version); if (ret >= 0) printf(" %s: %s\n", name, version); free(name); free(version); ret = blosc_get_complib_info("zstd", &name, &version); if (ret >= 0) printf(" %s: %s\n", name, version); free(name); free(version); } int main(int argc, char* argv[]) { char compressor[32]; char shuffle[32] = "shuffle"; char bsuite[32]; int single = 1; int suite = 0; int hard_suite = 0; int extreme_suite = 0; int debug_suite = 0; int nthreads = 8; /* The number of threads */ int size = 8 * MB; /* Buffer size */ int elsize = 4; /* Datatype size */ int rshift = 19; /* Significant bits */ int workingset = 256 * MB; /* The maximum allocated memory */ int nthreads_, size_, elsize_, rshift_, i; FILE* output_file = stdout; blosc_timestamp_t last, current; double totaltime; char usage[256]; print_compress_info(); strncpy(usage, "Usage: bench [blosclz | lz4 | lz4hc | zlib | zstd] " "[noshuffle | shuffle | bitshuffle] " "[single | suite | hardsuite | extremesuite | debugsuite] " "[nthreads] [bufsize(bytes)] [typesize] [sbits]", 255); if (argc < 1) { printf("%s\n", usage); exit(1); } if (argc >= 2) { strcpy(compressor, argv[1]); } else { strcpy(compressor, "blosclz"); } if (strcmp(compressor, "blosclz") != 0 && strcmp(compressor, "lz4") != 0 && strcmp(compressor, "lz4hc") != 0 && strcmp(compressor, "zlib") != 0 && strcmp(compressor, "zstd") != 0) { printf("No such compressor: '%s'\n", compressor); printf("%s\n", usage); exit(2); } if (argc >= 3) { strcpy(shuffle, argv[2]); if (strcmp(shuffle, "shuffle") != 0 && strcmp(shuffle, "bitshuffle") != 0 && strcmp(shuffle, "noshuffle") != 0) { printf("No such shuffler: '%s'\n", shuffle); printf("%s\n", usage); exit(2); } } if (argc < 4) strcpy(bsuite, "single"); else strcpy(bsuite, argv[3]); if (strcmp(bsuite, "single") == 0) { single = 1; } else if (strcmp(bsuite, "test") == 0) { single = 1; workingset /= 2; } else if (strcmp(bsuite, "suite") == 0) { suite = 1; } else if (strcmp(bsuite, "hardsuite") == 0) { hard_suite = 1; workingset /= 4; /* Values here are ending points for loops */ nthreads = 2; size = 8 * MB; elsize = 32; rshift = 32; } else if (strcmp(bsuite, "extremesuite") == 0) { extreme_suite = 1; workingset /= 8; niter = 1; /* Values here are ending points for loops */ nthreads = 4; size = 16 * MB; elsize = 32; rshift = 32; } else if (strcmp(bsuite, "debugsuite") == 0) { debug_suite = 1; workingset /= 8; niter = 1; /* Warning: values here are starting points for loops. This is useful for debugging. */ nthreads = 1; size = 16 * KB; elsize = 1; rshift = 0; } else { printf("%s\n", usage); exit(1); } printf("Using compressor: %s\n", compressor); printf("Using shuffle type: %s\n", shuffle); printf("Running suite: %s\n", bsuite); if (argc >= 5) { nthreads = (int)strtol(argv[4], NULL, 10); } if (argc >= 6) { size = (int)strtol(argv[5], NULL, 10); } if (argc >= 7) { elsize = (int)strtol(argv[6], NULL, 10); } if (argc >= 8) { rshift = (int)strtol(argv[7], NULL, 10); } if ((argc >= 9) || !(single || suite || hard_suite || extreme_suite)) { printf("%s\n", usage); exit(1); } nchunks = get_nchunks(size, workingset); blosc_set_timestamp(&last); blosc_init(); if (suite) { for (nthreads_ = 1; nthreads_ <= nthreads; nthreads_++) { do_bench(compressor, shuffle, nthreads_, size, elsize, rshift, output_file); } } else if (hard_suite) { /* Let's start the rshift loop by 4 so that 19 is visited. This is to allow a direct comparison with the plain suite, that runs precisely at 19 significant bits. */ for (rshift_ = 4; rshift_ <= rshift; rshift_ += 5) { for (elsize_ = 1; elsize_ <= elsize; elsize_ *= 2) { /* The next loop is for getting sizes that are not power of 2 */ for (i = -elsize_; i <= elsize_; i += elsize_) { for (size_ = 32 * KB; size_ <= size; size_ *= 2) { nchunks = get_nchunks(size_ + i, workingset); niter = 1; for (nthreads_ = 1; nthreads_ <= nthreads; nthreads_++) { do_bench(compressor, shuffle, nthreads_, size_ + i, elsize_, rshift_, output_file); blosc_set_timestamp(&current); totaltime = blosc_elapsed_secs(last, current); printf("Elapsed time:\t %6.1f s. Processed data: %.1f GB\n", totaltime, totalsize / GB); } } } } } } else if (extreme_suite) { for (rshift_ = 0; rshift_ <= rshift; rshift_++) { for (elsize_ = 1; elsize_ <= elsize; elsize_++) { /* The next loop is for getting sizes that are not power of 2 */ for (i = -elsize_ * 2; i <= elsize_ * 2; i += elsize_) { for (size_ = 32 * KB; size_ <= size; size_ *= 2) { nchunks = get_nchunks(size_ + i, workingset); for (nthreads_ = 1; nthreads_ <= nthreads; nthreads_++) { do_bench(compressor, shuffle, nthreads_, size_ + i, elsize_, rshift_, output_file); blosc_set_timestamp(&current); totaltime = blosc_elapsed_secs(last, current); printf("Elapsed time:\t %6.1f s. Processed data: %.1f GB\n", totaltime, totalsize / GB); } } } } } } else if (debug_suite) { for (rshift_ = rshift; rshift_ <= 32; rshift_++) { for (elsize_ = elsize; elsize_ <= 32; elsize_++) { /* The next loop is for getting sizes that are not power of 2 */ for (i = -elsize_ * 2; i <= elsize_ * 2; i += elsize_) { for (size_ = size; size_ <= (int) (16 * MB); size_ *= 2) { nchunks = get_nchunks(size_ + i, workingset); for (nthreads_ = nthreads; nthreads_ <= 6; nthreads_++) { do_bench(compressor, shuffle, nthreads_, size_ + i, elsize_, rshift_, output_file); blosc_set_timestamp(&current); totaltime = blosc_elapsed_secs(last, current); printf("Elapsed time:\t %6.1f s. Processed data: %.1f GB\n", totaltime, totalsize / GB); } } } } } } /* Single mode */ else { do_bench(compressor, shuffle, nthreads, size, elsize, rshift, output_file); } /* Print out some statistics */ blosc_set_timestamp(&current); totaltime = (float)blosc_elapsed_secs(last, current); printf("\nRound-trip compr/decompr on %.1f GB\n", totalsize / GB); printf("Elapsed time:\t %6.1f s, %.1f MB/s\n", totaltime, totalsize * 2 * 1.1 / (MB * totaltime)); /* Free blosc resources */ blosc_free_resources(); blosc_destroy(); return 0; }
clayne/c-blosc2
tests/fuzz/fuzz_compress_frame.c
<gh_stars>0 #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <inttypes.h> #include <blosc2.h> #ifdef __cplusplus extern "C" { #endif int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { const char *compressors[] = { "blosclz", "lz4", "lz4hc", "zlib", "zstd" }; int32_t i = 0, dsize = 0, filter = BLOSC_BITSHUFFLE; int32_t nchunk = 0, max_chunksize = 512; int64_t nchunks = 0; blosc_init(); blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.typesize = 1; /* Find next available compressor */ cparams.compcode = 0; while (blosc_set_compressor(compressors[cparams.compcode % 6]) == -1 && i < 6) { cparams.compcode++, i++; } if (i == 6) { /* No compressors available */ blosc_destroy(); return 0; } if (size > 0) { /* Variable size compression level and max chunksize */ cparams.clevel = data[0] % (9 + 1); max_chunksize *= data[0]; } if (size > 1) { filter = data[1]; } cparams.filters[BLOSC2_MAX_FILTERS - 1] = filter % (BLOSC_BITSHUFFLE + 1); cparams.filters_meta[BLOSC2_MAX_FILTERS - 1] = filter; cparams.nthreads = 1; blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS; dparams.nthreads = 1; /* Create a super-chunk backed by an in-memory frame */ blosc2_storage storage = {.cparams=&cparams, .dparams=&dparams}; blosc2_schunk* schunk = blosc2_schunk_new(&storage); if (schunk == NULL) { blosc_destroy(); return 0; } /* Compress data */ int32_t chunksize = max_chunksize; for (i = 0; chunksize > 0 && i < (int32_t)size; i += chunksize, nchunks++) { if (i + chunksize > (int32_t)size) chunksize = (int32_t)size - i; nchunks = blosc2_schunk_append_buffer(schunk, (uint8_t *)data + i, chunksize); if (nchunks < 0) { printf("Compression error. Error code: %" PRId64 "\n", nchunks); break; } } /* Decompress data */ uint8_t *uncompressed_data = (uint8_t *)malloc(size+1); if (uncompressed_data != NULL) { for (i = 0, nchunk = 0; nchunk < nchunks-1; nchunk++) { dsize = blosc2_schunk_decompress_chunk(schunk, nchunk, uncompressed_data + i, chunksize); if (dsize < 0) { printf("Decompression error. Error code: %d\n", dsize); break; } i += dsize; } /* Compare decompressed data with original */ if (size > 0 && nchunks > 0) { if (dsize < 0 || memcmp(data, uncompressed_data, size) != 0) { printf("Decompression data does not match original %d\n", dsize); } } free(uncompressed_data); } /* Free resources */ blosc2_schunk_free(schunk); blosc_destroy(); return 0; } #ifdef __cplusplus } #endif
clayne/c-blosc2
plugins/codecs/ndlz/ndlz.h
/********************************************************************* Blosc - Blocked Shuffling and Compression Library Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ #ifndef NDLZ_H #define NDLZ_H #include "context.h" #if defined (__cplusplus) extern "C" { #endif int ndlz_compress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_cparams *cparams, const void* chunk); int ndlz_decompress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_dparams *dparams, const void* chunk); #if defined (__cplusplus) } #endif #endif /* NDLZ_H */
clayne/c-blosc2
plugins/codecs/zfp/blosc2-zfp.c
#include "blosc2.h" #include "frame.h" #include "blosc2/codecs-registry.h" #include "zfp.h" #include "blosc2-zfp.h" #include <math.h> #include "context.h" #include "assert.h" #include "../plugins/plugin_utils.h" int zfp_acc_compress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_cparams *cparams, const void* chunk) { BLOSC_UNUSED_PARAM(chunk); ZFP_ERROR_NULL(input); ZFP_ERROR_NULL(output); ZFP_ERROR_NULL(cparams); double tol = (int8_t) meta; int8_t ndim; int64_t *shape = malloc(8 * sizeof(int64_t)); int32_t *chunkshape = malloc(8 * sizeof(int32_t)); int32_t *blockshape = malloc(8 * sizeof(int32_t)); uint8_t *smeta; int32_t smeta_len; if (blosc2_meta_get(cparams->schunk, "caterva", &smeta, &smeta_len) < 0) { printf("Blosc error"); free(shape); free(chunkshape); free(blockshape); return -1; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); zfp_type type; /* array scalar type */ zfp_field *field; /* array meta data */ zfp_stream *zfp; /* stream containing the real output buffer */ zfp_stream *zfp_aux; /* auxiliar compressed stream */ bitstream *stream; /* bit stream to write to or read from */ bitstream *stream_aux; /* auxiliar bit stream to write to or read from */ size_t zfpsize; /* byte size of compressed stream */ double tolerance = pow(10, tol); int32_t typesize = cparams->typesize; switch (typesize) { case sizeof(float): type = zfp_type_float; break; case sizeof(double): type = zfp_type_double; break; default: printf("\n ZFP is not available for this typesize \n"); free(shape); free(chunkshape); free(blockshape); return 0; } zfp = zfp_stream_open(NULL); zfp_stream_set_accuracy(zfp, tolerance); stream = stream_open(output, output_len); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); switch (ndim) { case 1: field = zfp_field_1d((void *) input, type, blockshape[0]); break; case 2: field = zfp_field_2d((void *) input, type, blockshape[1], blockshape[0]); break; case 3: field = zfp_field_3d((void *) input, type, blockshape[2], blockshape[1], blockshape[0]); break; case 4: field = zfp_field_4d((void *) input, type, blockshape[3], blockshape[2], blockshape[1], blockshape[0]); break; default: printf("\n ZFP is not available for this number of dims \n"); free(shape); free(chunkshape); free(blockshape); return 0; } int zfp_maxout = (int) zfp_stream_maximum_size(zfp, field); zfp_stream_close(zfp); stream_close(stream); uint8_t *aux_out = malloc(zfp_maxout); zfp_aux = zfp_stream_open(NULL); zfp_stream_set_accuracy(zfp_aux, tolerance); stream_aux = stream_open(aux_out, zfp_maxout); zfp_stream_set_bit_stream(zfp_aux, stream_aux); zfp_stream_rewind(zfp_aux); zfpsize = zfp_compress(zfp_aux, field); /* clean up */ zfp_field_free(field); zfp_stream_close(zfp_aux); stream_close(stream_aux); free(shape); free(chunkshape); free(blockshape); if (zfpsize == 0) { BLOSC_TRACE_ERROR("\n ZFP: Compression failed\n"); free(aux_out); return (int) zfpsize; } if ((int32_t) zfpsize >= input_len) { BLOSC_TRACE_ERROR("\n ZFP: Compressed data is bigger than input! \n"); free(aux_out); return 0; } memcpy(output, aux_out, zfpsize); free(aux_out); return (int) zfpsize; } int zfp_acc_decompress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_dparams *dparams, const void* chunk) { ZFP_ERROR_NULL(input); ZFP_ERROR_NULL(output); ZFP_ERROR_NULL(dparams); size_t typesize; int flags; blosc_cbuffer_metainfo(chunk, &typesize, &flags); double tol = (int8_t) meta; int8_t ndim; int64_t *shape = malloc(8 * sizeof(int64_t)); int32_t *chunkshape = malloc(8 * sizeof(int32_t)); int32_t *blockshape = malloc(8 * sizeof(int32_t)); uint8_t *smeta; int32_t smeta_len; if (blosc2_meta_get(dparams->schunk, "caterva", &smeta, &smeta_len) < 0) { printf("Blosc error"); free(shape); free(chunkshape); free(blockshape); return -1; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); zfp_type type; /* array scalar type */ zfp_field *field; /* array meta data */ zfp_stream *zfp; /* compressed stream */ bitstream *stream; /* bit stream to write to or read from */ size_t zfpsize; /* byte size of compressed stream */ double tolerance = pow(10, tol); switch (typesize) { case sizeof(float): type = zfp_type_float; break; case sizeof(double): type = zfp_type_double; break; default: printf("\n ZFP is not available for this typesize \n"); free(shape); free(chunkshape); free(blockshape); return 0; } zfp = zfp_stream_open(NULL); zfp_stream_set_accuracy(zfp, tolerance); stream = stream_open((void*) input, input_len); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); switch (ndim) { case 1: field = zfp_field_1d((void *) output, type, blockshape[0]); break; case 2: field = zfp_field_2d((void *) output, type, blockshape[1], blockshape[0]); break; case 3: field = zfp_field_3d((void *) output, type, blockshape[2], blockshape[1], blockshape[0]); break; case 4: field = zfp_field_4d((void *) output, type, blockshape[3], blockshape[2], blockshape[1], blockshape[0]); break; default: printf("\n ZFP is not available for this number of dims \n"); free(shape); free(chunkshape); free(blockshape); return 0; } zfpsize = zfp_decompress(zfp, field); /* clean up */ zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); free(shape); free(chunkshape); free(blockshape); if (zfpsize == 0) { BLOSC_TRACE_ERROR("\n ZFP: Decompression failed\n"); return (int) zfpsize; } return (int) output_len; } int zfp_prec_compress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_cparams *cparams, const void* chunk) { BLOSC_UNUSED_PARAM(chunk); ZFP_ERROR_NULL(input); ZFP_ERROR_NULL(output); ZFP_ERROR_NULL(cparams); int8_t ndim; int64_t *shape = malloc(8 * sizeof(int64_t)); int32_t *chunkshape = malloc(8 * sizeof(int32_t)); int32_t *blockshape = malloc(8 * sizeof(int32_t)); uint8_t *smeta; int32_t smeta_len; if (blosc2_meta_get(cparams->schunk, "caterva", &smeta, &smeta_len) < 0) { printf("Blosc error"); free(shape); free(chunkshape); free(blockshape); return -1; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); zfp_type type; /* array scalar type */ zfp_field *field; /* array meta data */ zfp_stream *zfp; /* stream containing the real output buffer */ zfp_stream *zfp_aux; /* auxiliar compressed stream */ bitstream *stream; /* bit stream to write to or read from */ bitstream *stream_aux; /* auxiliar bit stream to write to or read from */ size_t zfpsize; /* byte size of compressed stream */ uint prec; switch (ndim) { case 1: prec = meta + 5; break; case 2: prec = meta + 7; break; case 3: prec = meta + 9; break; case 4: prec = meta + 11; break; default: printf("\n ZFP is not available for this ndim \n"); free(shape); free(chunkshape); free(blockshape); return 0; } if(prec > ZFP_MAX_PREC) { BLOSC_TRACE_ERROR("Max precision for this codecs is %d", ZFP_MAX_PREC); prec = ZFP_MAX_PREC; } int32_t typesize = cparams->typesize; switch (typesize) { case sizeof(float): type = zfp_type_float; break; case sizeof(double): type = zfp_type_double; break; default: printf("\n ZFP is not available for this typesize \n"); free(shape); free(chunkshape); free(blockshape); return 0; } zfp = zfp_stream_open(NULL); zfp_stream_set_precision(zfp, prec); stream = stream_open(output, output_len); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); switch (ndim) { case 1: field = zfp_field_1d((void *) input, type, blockshape[0]); break; case 2: field = zfp_field_2d((void *) input, type, blockshape[1], blockshape[0]); break; case 3: field = zfp_field_3d((void *) input, type, blockshape[2], blockshape[1], blockshape[0]); break; case 4: field = zfp_field_4d((void *) input, type, blockshape[3], blockshape[2], blockshape[1], blockshape[0]); break; default: printf("\n ZFP is not available for this number of dims \n"); free(shape); free(chunkshape); free(blockshape); return 0; } int zfp_maxout = (int) zfp_stream_maximum_size(zfp, field); zfp_stream_close(zfp); stream_close(stream); uint8_t *aux_out = malloc(zfp_maxout); zfp_aux = zfp_stream_open(NULL); zfp_stream_set_precision(zfp_aux, prec); stream_aux = stream_open(aux_out, zfp_maxout); zfp_stream_set_bit_stream(zfp_aux, stream_aux); zfp_stream_rewind(zfp_aux); zfpsize = zfp_compress(zfp_aux, field); /* clean up */ zfp_field_free(field); zfp_stream_close(zfp_aux); stream_close(stream_aux); free(shape); free(chunkshape); free(blockshape); if (zfpsize == 0) { BLOSC_TRACE_ERROR("\n ZFP: Compression failed\n"); free(aux_out); return (int) zfpsize; } if ((int32_t) zfpsize >= input_len) { BLOSC_TRACE_ERROR("\n ZFP: Compressed data is bigger than input! \n"); free(aux_out); return 0; } memcpy(output, aux_out, zfpsize); free(aux_out); return (int) zfpsize; } int zfp_prec_decompress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_dparams *dparams, const void* chunk) { ZFP_ERROR_NULL(input); ZFP_ERROR_NULL(output); ZFP_ERROR_NULL(dparams); size_t typesize; int flags; blosc_cbuffer_metainfo(chunk, &typesize, &flags); int8_t ndim; int64_t *shape = malloc(8 * sizeof(int64_t)); int32_t *chunkshape = malloc(8 * sizeof(int32_t)); int32_t *blockshape = malloc(8 * sizeof(int32_t)); uint8_t *smeta; int32_t smeta_len; if (blosc2_meta_get(dparams->schunk, "caterva", &smeta, &smeta_len) < 0) { printf("Blosc error"); free(shape); free(chunkshape); free(blockshape); return -1; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); zfp_type type; /* array scalar type */ zfp_field *field; /* array meta data */ zfp_stream *zfp; /* compressed stream */ bitstream *stream; /* bit stream to write to or read from */ size_t zfpsize; /* byte size of compressed stream */ uint prec; switch (ndim) { case 1: prec = meta + 5; break; case 2: prec = meta + 7; break; case 3: prec = meta + 9; break; case 4: prec = meta + 11; break; default: printf("\n ZFP is not available for this ndim \n"); free(shape); free(chunkshape); free(blockshape); return 0; } if(prec > ZFP_MAX_PREC) { BLOSC_TRACE_ERROR("Max precision for this codecs is %d", ZFP_MAX_PREC); prec = ZFP_MAX_PREC; } switch (typesize) { case sizeof(float): type = zfp_type_float; break; case sizeof(double): type = zfp_type_double; break; default: printf("\n ZFP is not available for this typesize \n"); free(shape); free(chunkshape); free(blockshape); return 0; } zfp = zfp_stream_open(NULL); zfp_stream_set_precision(zfp, prec); stream = stream_open((void*) input, input_len); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); switch (ndim) { case 1: field = zfp_field_1d((void *) output, type, blockshape[0]); break; case 2: field = zfp_field_2d((void *) output, type, blockshape[1], blockshape[0]); break; case 3: field = zfp_field_3d((void *) output, type, blockshape[2], blockshape[1], blockshape[0]); break; case 4: field = zfp_field_4d((void *) output, type, blockshape[3], blockshape[2], blockshape[1], blockshape[0]); break; default: printf("\n ZFP is not available for this number of dims \n"); free(shape); free(chunkshape); free(blockshape); return 0; } zfpsize = zfp_decompress(zfp, field); /* clean up */ zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); free(shape); free(chunkshape); free(blockshape); if (zfpsize == 0) { BLOSC_TRACE_ERROR("\n ZFP: Decompression failed\n"); return (int) zfpsize; } return (int) output_len; } int zfp_rate_compress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_cparams *cparams, const void* chunk) { BLOSC_UNUSED_PARAM(chunk); ZFP_ERROR_NULL(input); ZFP_ERROR_NULL(output); ZFP_ERROR_NULL(cparams); double ratio = (double) meta / 100.0; int8_t ndim; int64_t *shape = malloc(8 * sizeof(int64_t)); int32_t *chunkshape = malloc(8 * sizeof(int32_t)); int32_t *blockshape = malloc(8 * sizeof(int32_t)); uint8_t *smeta; int32_t smeta_len; if (blosc2_meta_get(cparams->schunk, "caterva", &smeta, &smeta_len) < 0) { printf("Blosc error"); free(shape); free(chunkshape); free(blockshape); return -1; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); zfp_type type; /* array scalar type */ zfp_field *field; /* array meta data */ zfp_stream *zfp; /* stream containing the real output buffer */ zfp_stream *zfp_aux; /* auxiliar compressed stream */ bitstream *stream; /* bit stream to write to or read from */ bitstream *stream_aux; /* auxiliar bit stream to write to or read from */ size_t zfpsize; /* byte size of compressed stream */ int32_t typesize = cparams->typesize; switch (typesize) { case sizeof(float): type = zfp_type_float; break; case sizeof(double): type = zfp_type_double; break; default: printf("\n ZFP is not available for this typesize \n"); return 0; } double rate = ratio * typesize * 8; // convert from output size / input size to output bits per input value uint cellsize = 1u << (2 * ndim); double min_rate; switch (type) { case zfp_type_float: min_rate = (double) (1 + 8u) / cellsize; if (rate < min_rate) { BLOSC_TRACE_ERROR("\n ZFP minimum rate for this item type is %f. Compression will be done using this rate \n", min_rate); } break; case zfp_type_double: min_rate = (double) (1 + 11u) / cellsize; if (rate < min_rate) { BLOSC_TRACE_ERROR("\n ZFP minimum rate for this item type is %f. Compression will be done using this rate \n", min_rate); } break; default: free(shape); free(chunkshape); free(blockshape); return 0; } zfp = zfp_stream_open(NULL); stream = stream_open(output, output_len); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); switch (ndim) { case 1: field = zfp_field_1d((void *) input, type, blockshape[0]); break; case 2: field = zfp_field_2d((void *) input, type, blockshape[1], blockshape[0]); break; case 3: field = zfp_field_3d((void *) input, type, blockshape[2], blockshape[1], blockshape[0]); break; case 4: field = zfp_field_4d((void *) input, type, blockshape[3], blockshape[2], blockshape[1], blockshape[0]); break; default: printf("\n ZFP is not available for this number of dims \n"); free(shape); free(chunkshape); free(blockshape); return 0; } int zfp_maxout = (int) zfp_stream_maximum_size(zfp, field); zfp_stream_close(zfp); stream_close(stream); uint8_t *aux_out = malloc(zfp_maxout); zfp_aux = zfp_stream_open(NULL); stream_aux = stream_open(aux_out, zfp_maxout); zfp_stream_set_bit_stream(zfp_aux, stream_aux); zfp_stream_rewind(zfp_aux); zfp_stream_set_rate(zfp_aux, rate, type, ndim, zfp_false); zfpsize = zfp_compress(zfp_aux, field); /* clean up */ zfp_field_free(field); zfp_stream_close(zfp_aux); stream_close(stream_aux); free(shape); free(chunkshape); free(blockshape); if (zfpsize == 0) { BLOSC_TRACE_ERROR("\n ZFP: Compression failed\n"); free(aux_out); return (int) zfpsize; } if ((int32_t) zfpsize >= input_len) { BLOSC_TRACE_ERROR("\n ZFP: Compressed data is bigger than input! \n"); free(aux_out); return 0; } memcpy(output, aux_out, zfpsize); free(aux_out); return (int) zfpsize; } int zfp_rate_decompress(const uint8_t *input, int32_t input_len, uint8_t *output, int32_t output_len, uint8_t meta, blosc2_dparams *dparams, const void* chunk) { ZFP_ERROR_NULL(input); ZFP_ERROR_NULL(output); ZFP_ERROR_NULL(dparams); size_t typesize; int flags; blosc_cbuffer_metainfo(chunk, &typesize, &flags); double ratio = (double) meta / 100.0; int8_t ndim; int64_t *shape = malloc(8 * sizeof(int64_t)); int32_t *chunkshape = malloc(8 * sizeof(int32_t)); int32_t *blockshape = malloc(8 * sizeof(int32_t)); uint8_t *smeta; int32_t smeta_len; if (blosc2_meta_get(dparams->schunk, "caterva", &smeta, &smeta_len) < 0) { printf("Blosc error"); free(shape); free(chunkshape); free(blockshape); return -1; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); zfp_type type; /* array scalar type */ zfp_field *field; /* array meta data */ zfp_stream *zfp; /* compressed stream */ bitstream *stream; /* bit stream to write to or read from */ size_t zfpsize; /* byte size of compressed stream */ switch (typesize) { case sizeof(float): type = zfp_type_float; break; case sizeof(double): type = zfp_type_double; break; default: printf("\n ZFP is not available for this typesize \n"); free(shape); free(chunkshape); free(blockshape); return 0; } double rate = ratio * (double) typesize * 8; // convert from output size / input size to output bits per input value zfp = zfp_stream_open(NULL); zfp_stream_set_rate(zfp, rate, type, ndim, zfp_false); stream = stream_open((void*) input, input_len); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); switch (ndim) { case 1: field = zfp_field_1d((void *) output, type, blockshape[0]); break; case 2: field = zfp_field_2d((void *) output, type, blockshape[1], blockshape[0]); break; case 3: field = zfp_field_3d((void *) output, type, blockshape[2], blockshape[1], blockshape[0]); break; case 4: field = zfp_field_4d((void *) output, type, blockshape[3], blockshape[2], blockshape[1], blockshape[0]); break; default: printf("\n ZFP is not available for this number of dims \n"); free(shape); free(chunkshape); free(blockshape); return 0; } zfpsize = zfp_decompress(zfp, field); /* clean up */ zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); free(shape); free(chunkshape); free(blockshape); if (zfpsize == 0) { BLOSC_TRACE_ERROR("\n ZFP: Decompression failed\n"); return (int) zfpsize; } return (int) output_len; } int zfp_getcell(blosc2_context *context, const uint8_t *block, int32_t cbytes, uint8_t *dest, int32_t destsize) { bool meta = false; uint8_t ndim = ZFP_MAX_DIM + 1; int32_t blockshape[4]; // ZFP only works for caterva datasets for (int nmetalayer = 0; nmetalayer < context->schunk->nmetalayers; nmetalayer++) { if (strcmp("caterva", context->schunk->metalayers[nmetalayer]->name) == 0) { meta = true; uint8_t *pmeta = context->schunk->metalayers[nmetalayer]->content; ndim = (int8_t) pmeta[2]; pmeta += (6 + ndim * 9 + ndim * 5); for (int8_t i = 0; (uint8_t) i < ndim; i++) { pmeta += 1; swap_store(blockshape + i, pmeta, sizeof(int32_t)); pmeta += sizeof(int32_t); } } } if (!meta) { return -1; } assert(ndim <= ZFP_MAX_DIM); int64_t cell_start_ndim[4], cell_ind_ndim[4], ncell_ndim[4], ind_strides[4], cell_strides[4]; int64_t cell_ind, ncell; int cellshape = 4; index_unidim_to_multidim(ndim, blockshape, context->zfp_cell_start, cell_start_ndim); for (int i = 0; i < ndim; ++i) { cell_ind_ndim[i] = cell_start_ndim[i] % cellshape; ncell_ndim[i] = cell_start_ndim[i] / cellshape; } ind_strides[ndim - 1] = cell_strides[ndim - 1] = 1; for (int i = ndim - 2; i >= 0; --i) { ind_strides[i] = cellshape * ind_strides[i + 1]; cell_strides[i] = ((blockshape[i + 1] - 1) / cellshape + 1) * cell_strides[i + 1]; } index_multidim_to_unidim(cell_ind_ndim, (int8_t) ndim, ind_strides, &cell_ind); index_multidim_to_unidim(ncell_ndim, (int8_t) ndim, cell_strides, &ncell); int cell_nitems = (int) (1u << (2 * ndim)); if ((context->zfp_cell_nitems > cell_nitems) || ((cell_ind + context->zfp_cell_nitems) > cell_nitems)) { return 0; } // Get the ZFP stream zfp_type type; /* array scalar type */ zfp_stream *zfp; /* compressed stream */ bitstream *stream; /* bit stream to write to or read from */ int32_t typesize = context->typesize; zfp = zfp_stream_open(NULL); switch (typesize) { case sizeof(float): type = zfp_type_float; break; case sizeof(double): type = zfp_type_double; break; default: printf("\n ZFP is not available for this typesize \n"); return 0; } uint8_t compmeta = context->compcode_meta; // access to compressed chunk header double rate = (double) (compmeta * typesize * 8) / 100.0; // convert from output size / input size to output bits per input value zfp_stream_set_rate(zfp, rate, type, ndim, zfp_false); stream = stream_open((void *) block, cbytes); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); // Check that ncell is a valid index int ncells = (int) ((cbytes * 8) / zfp->maxbits); if (ncell >= ncells) { BLOSC_TRACE_ERROR("Invalid cell index"); return -1; } // Position the stream at the ncell bit offset for reading stream_rseek(zfp->stream, (size_t) (ncell * zfp->maxbits)); // Get the cell size_t zfpsize; uint8_t *cell = malloc(cell_nitems * typesize); switch (ndim) { case 1: switch (type) { case zfp_type_float: zfpsize = zfp_decode_block_float_1(zfp, (float *) cell); break; case zfp_type_double: zfpsize = zfp_decode_block_double_1(zfp, (double *) cell); break; default: printf("\n ZFP is not available for this typesize \n"); zfp_stream_close(zfp); stream_close(stream); return 0; } break; case 2: switch (type) { case zfp_type_float: zfpsize = zfp_decode_block_float_2(zfp, (float *) cell); break; case zfp_type_double: zfpsize = zfp_decode_block_double_2(zfp, (double *) cell); break; default: printf("\n ZFP is not available for this typesize \n"); zfp_stream_close(zfp); stream_close(stream); return 0; } break; case 3: switch (type) { case zfp_type_float: zfpsize = zfp_decode_block_float_3(zfp, (float *) cell); break; case zfp_type_double: zfpsize = zfp_decode_block_double_3(zfp, (double *) cell); break; default: printf("\n ZFP is not available for this typesize \n"); zfp_stream_close(zfp); stream_close(stream); return 0; } break; case 4: switch (type) { case zfp_type_float: zfpsize = zfp_decode_block_float_4(zfp, (float *) cell); break; case zfp_type_double: zfpsize = zfp_decode_block_double_4(zfp, (double *) cell); break; default: printf("\n ZFP is not available for this typesize \n"); zfp_stream_close(zfp); stream_close(stream); return 0; } break; default: printf("\n ZFP is not available for this number of dims \n"); return 0; } memcpy(dest, &cell[cell_ind * typesize], context->zfp_cell_nitems * typesize); zfp_stream_close(zfp); stream_close(stream); free(cell); if ((zfpsize == 0) || ((int32_t)zfpsize > (destsize * 8)) || ((int32_t)zfpsize > (cell_nitems * typesize * 8)) || ((context->zfp_cell_nitems * typesize * 8) > (int32_t)zfpsize)) { BLOSC_TRACE_ERROR("ZFP error or small destsize"); return -1; } return (int) (context->zfp_cell_nitems * typesize); }
clayne/c-blosc2
contrib/shuffle_neon/shuffle8_neon/shuffle8_neon_vtbx_bucle.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <arm_neon.h> #include <string.h> static void printmem8(uint8x8_t buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x\n", buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem16(uint8x16_t r0) { uint8_t buf[16]; ((uint8x16_t *)buf)[0] = r0; printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem(uint8_t* buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x," "%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[31], buf[30], buf[29], buf[28], buf[27], buf[26], buf[25], buf[24], buf[23], buf[22], buf[21], buf[20], buf[19], buf[18], buf[17], buf[16], buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } /* Routine optimized for shuffling a buffer for a type size of 8 bytes. */ void shuffle8_neon(uint8_t* const dest, const uint8_t* const src, const size_t vectorizable_elements, const size_t total_elements) { size_t i, j, k, l; static const size_t bytesoftype = 8; uint8x8x4_t r0[2], r1[2]; uint8_t *index = "\x00\x08\x10\x18\x01\x09\x11\x19" "\x02\x0a\x12\x1a\x03\x0b\x13\x1b" "\x04\x0c\x14\x1c\x05\x0d\x15\x1d" "\x06\x0e\x16\x1e\x07\x0f\x17\x1f"; uint8_t *index_top = "\x00\x01\x02\x03\xff\xff\xff\xff" "\x04\x05\x06\x07\xff\xff\xff\xff" "\x08\x09\x0a\x0b\xff\xff\xff\xff" "\x0c\x0d\x0e\x0f\xff\xff\xff\xff" "\x10\x11\x12\x13\xff\xff\xff\xff" "\x14\x15\x16\x17\xff\xff\xff\xff" "\x18\x19\x1a\x1b\xff\xff\xff\xff" "\x1c\x1d\x1e\x1f\xff\xff\xff\xff"; uint8_t *index_bottom = "\xff\xff\xff\xff\x00\x01\x02\x03" "\xff\xff\xff\xff\x04\x05\x06\x07" "\xff\xff\xff\xff\x08\x09\x0a\x0b" "\xff\xff\xff\xff\x0c\x0d\x0e\x0f" "\xff\xff\xff\xff\x10\x11\x12\x13" "\xff\xff\xff\xff\x14\x15\x16\x17" "\xff\xff\xff\xff\x18\x19\x1a\x1b" "\xff\xff\xff\xff\x1c\x1d\x1e\x1f"; for(i = 0, k = 0; i < vectorizable_elements*bytesoftype; i += 2*sizeof(r0[0]), k++) { /* Load 8 byte groups to the structures */ for(j = 0; j < 4; j++) { for (l = 0; l < 2; l++) { r0[l].val[j] = vld1_u8(src + l*32 + k*32 + k*sizeof(r0[l]) + j*sizeof(r0[l].val[j])); } } /* Table look up to separate bytes */ for(j = 0; j < 4; j++) { for (l = 0; l < 2; l++) { r1[l].val[j] = vtbl4_u8(r0[l], vld1_u8(index + j*sizeof(r1[l].val[j]))); } } /* Rearrange the distribution of the structures */ for(j = 0; j < 4; j++) { r0[0].val[j] = vtbx4_u8(r0[0].val[j], r1[0], vld1_u8(index_top + j*sizeof(r0[0].val[j]))); r0[0].val[j] = vtbx4_u8(r0[0].val[j], r1[1], vld1_u8(index_bottom + j*sizeof(r0[0].val[j]))); r0[1].val[j] = vtbx4_u8(r0[1].val[j], r1[0], vld1_u8(index_top + 32 + j*sizeof(r0[1].val[j]))); r0[1].val[j] = vtbx4_u8(r0[1].val[j], r1[1], vld1_u8(index_bottom + 32 + j*sizeof(r0[1].val[j]))); } /* Store the results in the destination vector */ for(j = 0; j < 4; j++) { for (l = 0; l < 2; l++) { vst1_u8(dest + total_elements*(j+l*4) + k*sizeof(r0[l].val[j]), r0[l].val[j]); } } } } void main() { uint8_t *src = "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\x13\x21\x17\xc8\xc9\x34\x25\x11\x67\x74\x4e\xe8\x67\x74\x4e\xe8" "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\x13\x21\x17\xc8\xc9\x34\x25\x11\x67\x74\x4e\xe8\x67\x74\x4e\xe8"; uint8_t *dest = calloc(288,2); size_t vectorizable_elements = 32; size_t total_elements = 36; shuffle8_neon(dest, src, vectorizable_elements, total_elements); printf("vst1q_u8 \n"); printmem(dest); printmem(dest+32); printmem(dest+64); printmem(dest+96); printmem(dest+128); printmem(dest+160); printmem(dest+192); printmem(dest+224); printmem(dest+256); free(dest); }
clayne/c-blosc2
internal-complibs/zlib-ng-2.0.6/trees_emit.h
<gh_stars>0 #ifndef TREES_EMIT_H_ #define TREES_EMIT_H_ #include "zbuild.h" #include "trees.h" #ifdef ZLIB_DEBUG # include <ctype.h> # include <inttypes.h> # include <stdint.h> #endif /* trees.h */ extern Z_INTERNAL const ct_data static_ltree[L_CODES+2]; extern Z_INTERNAL const ct_data static_dtree[D_CODES]; extern const unsigned char Z_INTERNAL zng_dist_code[DIST_CODE_LEN]; extern const unsigned char Z_INTERNAL zng_length_code[MAX_MATCH-MIN_MATCH+1]; extern Z_INTERNAL const int base_length[LENGTH_CODES]; extern Z_INTERNAL const int base_dist[D_CODES]; /* Bit buffer and deflate code stderr tracing */ #ifdef ZLIB_DEBUG # define send_bits_trace(s, value, length) { \ Tracevv((stderr, " l %2d v %4llx ", (int)(length), (long long)(value))); \ Assert(length > 0 && length <= BIT_BUF_SIZE, "invalid length"); \ } # define send_code_trace(s, c) \ if (z_verbose > 2) { \ fprintf(stderr, "\ncd %3d ", (c)); \ } #else # define send_bits_trace(s, value, length) # define send_code_trace(s, c) #endif /* If not enough room in bi_buf, use (valid) bits from bi_buf and * (64 - bi_valid) bits from value, leaving (width - (64-bi_valid)) * unused bits in value. */ #define send_bits(s, t_val, t_len, bi_buf, bi_valid) {\ uint64_t val = (uint64_t)t_val;\ uint32_t len = (uint32_t)t_len;\ uint32_t total_bits = bi_valid + len;\ send_bits_trace(s, val, len);\ sent_bits_add(s, len);\ if (total_bits < BIT_BUF_SIZE) {\ bi_buf |= val << bi_valid;\ bi_valid = total_bits;\ } else if (bi_valid == BIT_BUF_SIZE) {\ put_uint64(s, bi_buf);\ bi_buf = val;\ bi_valid = len;\ } else {\ bi_buf |= val << bi_valid;\ put_uint64(s, bi_buf);\ bi_buf = val >> (BIT_BUF_SIZE - bi_valid);\ bi_valid = total_bits - BIT_BUF_SIZE;\ }\ } /* Send a code of the given tree. c and tree must not have side effects */ #ifdef ZLIB_DEBUG # define send_code(s, c, tree, bi_buf, bi_valid) { \ send_code_trace(s, c); \ send_bits(s, tree[c].Code, tree[c].Len, bi_buf, bi_valid); \ } #else # define send_code(s, c, tree, bi_buf, bi_valid) \ send_bits(s, tree[c].Code, tree[c].Len, bi_buf, bi_valid) #endif /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ static void bi_windup(deflate_state *s) { if (s->bi_valid > 56) { put_uint64(s, s->bi_buf); } else { if (s->bi_valid > 24) { put_uint32(s, (uint32_t)s->bi_buf); s->bi_buf >>= 32; s->bi_valid -= 32; } if (s->bi_valid > 8) { put_short(s, (uint16_t)s->bi_buf); s->bi_buf >>= 16; s->bi_valid -= 16; } if (s->bi_valid > 0) { put_byte(s, s->bi_buf); } } s->bi_buf = 0; s->bi_valid = 0; } /* =========================================================================== * Emit literal code */ static inline uint32_t zng_emit_lit(deflate_state *s, const ct_data *ltree, unsigned c) { uint32_t bi_valid = s->bi_valid; uint64_t bi_buf = s->bi_buf; send_code(s, c, ltree, bi_buf, bi_valid); s->bi_valid = bi_valid; s->bi_buf = bi_buf; Tracecv(isgraph(c & 0xff), (stderr, " '%c' ", c)); return ltree[c].Len; } /* =========================================================================== * Emit match distance/length code */ static inline uint32_t zng_emit_dist(deflate_state *s, const ct_data *ltree, const ct_data *dtree, uint32_t lc, uint32_t dist) { uint32_t c, extra; uint8_t code; uint64_t match_bits; uint32_t match_bits_len; uint32_t bi_valid = s->bi_valid; uint64_t bi_buf = s->bi_buf; /* Send the length code, len is the match length - MIN_MATCH */ code = zng_length_code[lc]; c = code+LITERALS+1; Assert(c < L_CODES, "bad l_code"); send_code_trace(s, c); match_bits = ltree[c].Code; match_bits_len = ltree[c].Len; extra = extra_lbits[code]; if (extra != 0) { lc -= base_length[code]; match_bits |= ((uint64_t)lc << match_bits_len); match_bits_len += extra; } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); Assert(code < D_CODES, "bad d_code"); send_code_trace(s, code); /* Send the distance code */ match_bits |= ((uint64_t)dtree[code].Code << match_bits_len); match_bits_len += dtree[code].Len; extra = extra_dbits[code]; if (extra != 0) { dist -= base_dist[code]; match_bits |= ((uint64_t)dist << match_bits_len); match_bits_len += extra; } send_bits(s, match_bits, match_bits_len, bi_buf, bi_valid); s->bi_valid = bi_valid; s->bi_buf = bi_buf; return match_bits_len; } /* =========================================================================== * Emit end block */ static inline void zng_emit_end_block(deflate_state *s, const ct_data *ltree, const int last) { uint32_t bi_valid = s->bi_valid; uint64_t bi_buf = s->bi_buf; send_code(s, END_BLOCK, ltree, bi_buf, bi_valid); s->bi_valid = bi_valid; s->bi_buf = bi_buf; Tracev((stderr, "\n+++ Emit End Block: Last: %u Pending: %u Total Out: %" PRIu64 "\n", last, s->pending, (uint64_t)s->strm->total_out)); Z_UNUSED(last); } /* =========================================================================== * Emit literal and count bits */ static inline void zng_tr_emit_lit(deflate_state *s, const ct_data *ltree, unsigned c) { cmpr_bits_add(s, zng_emit_lit(s, ltree, c)); } /* =========================================================================== * Emit match and count bits */ static inline void zng_tr_emit_dist(deflate_state *s, const ct_data *ltree, const ct_data *dtree, uint32_t lc, uint32_t dist) { cmpr_bits_add(s, zng_emit_dist(s, ltree, dtree, lc, dist)); } /* =========================================================================== * Emit start of block */ static inline void zng_tr_emit_tree(deflate_state *s, int type, const int last) { uint32_t bi_valid = s->bi_valid; uint64_t bi_buf = s->bi_buf; uint32_t header_bits = (type << 1) + last; send_bits(s, header_bits, 3, bi_buf, bi_valid); cmpr_bits_add(s, 3); s->bi_valid = bi_valid; s->bi_buf = bi_buf; Tracev((stderr, "\n--- Emit Tree: Last: %u\n", last)); } /* =========================================================================== * Align bit buffer on a byte boundary and count bits */ static inline void zng_tr_emit_align(deflate_state *s) { bi_windup(s); /* align on byte boundary */ sent_bits_align(s); } /* =========================================================================== * Emit an end block and align bit buffer if last block */ static inline void zng_tr_emit_end_block(deflate_state *s, const ct_data *ltree, const int last) { zng_emit_end_block(s, ltree, last); cmpr_bits_add(s, 7); if (last) zng_tr_emit_align(s); } #endif
clayne/c-blosc2
tests/test_small_chunks.c
<filename>tests/test_small_chunks.c /* Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) */ #include "test_common.h" #include "cutest.h" CUTEST_TEST_DATA(small_chunks) { bool fix_windows_compilation; }; CUTEST_TEST_SETUP(small_chunks) { blosc_init(); } CUTEST_TEST_TEST(small_chunks) { int64_t rc; int8_t itemsize = 8; int32_t nitems = 50 * 1000; int32_t chunksize = 10 * itemsize; int32_t blocksize = 10 * itemsize; int64_t nchunks = nitems * itemsize / chunksize; blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.blocksize = blocksize; blosc2_storage storage = BLOSC2_STORAGE_DEFAULTS; storage.cparams = &cparams; storage.urlpath = "ex_update.caterva"; blosc2_remove_dir("ex_update.caterva"); storage.contiguous = false; blosc2_schunk *sc = blosc2_schunk_new(&storage); int32_t chunk_nbytes = itemsize + BLOSC_MAX_OVERHEAD; uint8_t *chunk = malloc(chunk_nbytes); int64_t rep_val = 8; blosc2_chunk_repeatval(cparams, chunksize, chunk, chunk_nbytes, &rep_val); for (int i = 0; i < nchunks; ++i) { rc = blosc2_schunk_append_chunk(sc, chunk, true); CUTEST_ASSERT("Can not append chunk", rc == i + 1); } free(chunk); bool needs_free; rc = blosc2_schunk_get_chunk(sc, 999, &chunk, &needs_free); if (rc < 0) { return BLOSC2_ERROR_FAILURE; } CUTEST_ASSERT("Can not get chunk", rc >= 0); if (needs_free) { free(chunk); } blosc2_schunk_free(sc); blosc2_remove_dir("ex_update.caterva"); blosc_destroy(); return 0; } CUTEST_TEST_TEARDOWN(small_chunks) { blosc_destroy(); } int main() { CUTEST_TEST_RUN(small_chunks) }
clayne/c-blosc2
internal-complibs/zlib-ng-2.0.6/test/switchlevels.c
<gh_stars>100-1000 /* Compresses a user-specified number of chunks from stdin into stdout as a single gzip stream. * Each chunk is compressed with a user-specified level. */ #define _POSIX_SOURCE 1 /* This file needs POSIX for fileno(). */ #include "zbuild.h" #ifdef ZLIB_COMPAT # include "zlib.h" #else # include "zlib-ng.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(_WIN32) || defined(__CYGWIN__) # include <fcntl.h> # include <io.h> # define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) #else # define SET_BINARY_MODE(file) #endif static int read_all(unsigned char *buf, size_t size) { size_t total_read = 0; while (total_read < size) { size_t n_read = fread(buf + total_read, 1, size - total_read, stdin); if (ferror(stdin)) { perror("fread\n"); return 1; } if (n_read == 0) { fprintf(stderr, "Premature EOF\n"); return 1; } total_read += n_read; } return 0; } static int write_all(unsigned char *buf, size_t size) { size_t total_written = 0; while (total_written < size) { size_t n_written = fwrite(buf + total_written, 1, size - total_written, stdout); if (ferror(stdout)) { perror("fwrite\n"); return 1; } total_written += n_written; } return 0; } static int compress_chunk(PREFIX3(stream) *strm, int level, int size, int last) { int ret = 1; int err = 0; unsigned long compsize; unsigned char *buf; if (size <= 0) { fprintf(stderr, "compress_chunk() invalid size %d\n", size); goto done; } if (level < 0 || level > 9) { fprintf(stderr, "compress_chunk() invalid level %d\n", level); goto done; } compsize = PREFIX(deflateBound)(strm, size); buf = malloc(size + compsize); if (buf == NULL) { fprintf(stderr, "Out of memory\n"); goto done; } if (read_all(buf, size) != 0) { goto free_buf; } /* Provide only output buffer to deflateParams(). It might need some space to flush the leftovers from the last * deflate(), but we don't want it to compress anything new. */ strm->next_in = NULL; strm->avail_in = 0; strm->next_out = buf + size; strm->avail_out = compsize; err = PREFIX(deflateParams)(strm, level, Z_DEFAULT_STRATEGY); if (err != Z_OK) { fprintf(stderr, "deflateParams() failed with code %d\n", err); goto free_buf; } /* Provide input buffer to deflate(). */ strm->next_in = buf; strm->avail_in = size; err = PREFIX(deflate)(strm, last ? Z_FINISH : Z_SYNC_FLUSH); if ((!last && err != Z_OK) || (last && err != Z_STREAM_END)) { fprintf(stderr, "deflate() failed with code %d\n", err); goto free_buf; } if (strm->avail_in != 0) { fprintf(stderr, "deflate() did not consume %d bytes of input\n", strm->avail_in); goto free_buf; } if (write_all(buf + size, compsize - strm->avail_out) != 0) { goto free_buf; } ret = 0; free_buf: free(buf); done: return ret; } void show_help(void) { printf("Usage: switchlevels [-w bits] level1 size1 [level2 size2 ...]\n\n" \ " -w : window bits (8 to 15 for gzip, -8 to -15 for zlib)\n\n"); } int main(int argc, char **argv) { int ret = EXIT_FAILURE; int err = 0; int size = 0; int level = Z_DEFAULT_COMPRESSION; int level_arg = 1; int window_bits = MAX_WBITS + 16; PREFIX3(stream) strm; if ((argc == 1) || (argc == 2 && strcmp(argv[1], "--help") == 0)) { show_help(); return 0; } SET_BINARY_MODE(stdin); SET_BINARY_MODE(stdout); memset(&strm, 0, sizeof(strm)); for (int i = 1; i < argc - 1; i++) { if (strcmp(argv[i], "-w") == 0 && i+1 < argc) { window_bits = atoi(argv[++i]); } else { level_arg = i; level = atoi(argv[i]); break; } } err = PREFIX(deflateInit2)(&strm, level, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY); if (err != Z_OK) { fprintf(stderr, "deflateInit() failed with code %d\n", err); goto done; } for (int i = level_arg; i < argc - 1; i += 2) { level = atoi(argv[i]); size = atoi(argv[i + 1]); if (compress_chunk(&strm, level, size, i + 2 >= argc - 1) != 0) { goto deflate_end; } } ret = EXIT_SUCCESS; deflate_end: PREFIX(deflateEnd)(&strm); done: return ret; }
clayne/c-blosc2
plugins/codecs/zfp/test_zfp_rate_float.c
<filename>plugins/codecs/zfp/test_zfp_rate_float.c /********************************************************************* Blosc - Blocked Shuffling and Compression Library Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. Test program demonstrating use of the Blosc codec from C code. To compile this program: $ gcc -O test_zfp_rate_float.c -o test_zfp_rate_float -lblosc2 **********************************************************************/ #include <stdio.h> #include "blosc2.h" #include "blosc2/codecs-registry.h" #include <inttypes.h> static int test_zfp_rate_float(blosc2_schunk* schunk) { if (schunk->typesize != 4) { printf("Error: This test is only for doubles.\n"); return 0; } int64_t nchunks = schunk->nchunks; int32_t chunksize = (int32_t) (schunk->chunksize); float *data_in = malloc(chunksize); int decompressed; int64_t csize; int64_t dsize; int64_t csize_f = 0; uint8_t *data_out = malloc(chunksize + BLOSC_MAX_OVERHEAD); float *data_dest = malloc(chunksize); /* Create a context for compression */ int8_t zfp_rate = 37; blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.splitmode = BLOSC_NEVER_SPLIT; cparams.typesize = schunk->typesize; cparams.compcode = BLOSC_CODEC_ZFP_FIXED_RATE; cparams.compcode_meta = zfp_rate; cparams.filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_NOFILTER; cparams.clevel = 5; cparams.nthreads = 1; cparams.blocksize = schunk->blocksize; cparams.schunk = schunk; blosc2_context *cctx; cctx = blosc2_create_cctx(cparams); blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS; dparams.nthreads = 1; dparams.schunk = schunk; blosc2_context *dctx; dctx = blosc2_create_dctx(dparams); for (int ci = 0; ci < nchunks; ci++) { decompressed = blosc2_schunk_decompress_chunk(schunk, ci, data_in, chunksize); if (decompressed < 0) { printf("Error decompressing chunk \n"); return -1; } /* Compress with clevel=5 and shuffle active */ csize = blosc2_compress_ctx(cctx, data_in, chunksize, data_out, chunksize + BLOSC_MAX_OVERHEAD); if (csize == 0) { printf("Buffer is uncompressible. Giving up.\n"); return 0; } else if (csize < 0) { printf("Compression error. Error code: %" PRId64 "\n", csize); return (int) csize; } csize_f += csize; /* Decompress */ dsize = blosc2_decompress_ctx(dctx, data_out, chunksize + BLOSC_MAX_OVERHEAD, data_dest, chunksize); if (dsize <= 0) { printf("Decompression error. Error code: %" PRId64 "\n", dsize); return (int) dsize; } } csize_f = csize_f / nchunks; free(data_in); free(data_out); free(data_dest); blosc2_free_ctx(cctx); blosc2_free_ctx(dctx); printf("Succesful roundtrip!\n"); printf("Compression: %d -> %" PRId64 " (%.1fx)\n", chunksize, csize_f, (1. * chunksize) / (double) csize_f); return (int) (chunksize - csize_f); } static int test_zfp_rate_double(blosc2_schunk* schunk) { if (schunk->typesize != 8) { printf("Error: This test is only for doubles.\n"); return 0; } int64_t nchunks = schunk->nchunks; int32_t chunksize = (int32_t) (schunk->chunksize); double *data_in = malloc(chunksize); int decompressed; int64_t csize; int64_t dsize; int64_t csize_f = 0; uint8_t *data_out = malloc(chunksize + BLOSC_MAX_OVERHEAD); double *data_dest = malloc(chunksize); /* Create a context for compression */ int zfp_rate = 37; blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.splitmode = BLOSC_NEVER_SPLIT; cparams.typesize = schunk->typesize; cparams.compcode = BLOSC_CODEC_ZFP_FIXED_RATE; cparams.compcode_meta = zfp_rate; cparams.filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_NOFILTER; cparams.clevel = 5; cparams.nthreads = 1; cparams.blocksize = schunk->blocksize; cparams.schunk = schunk; blosc2_context *cctx; cctx = blosc2_create_cctx(cparams); blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS; dparams.nthreads = 1; dparams.schunk = schunk; blosc2_context *dctx; dctx = blosc2_create_dctx(dparams); for (int ci = 0; ci < nchunks; ci++) { decompressed = blosc2_schunk_decompress_chunk(schunk, ci, data_in, chunksize); if (decompressed < 0) { printf("Error decompressing chunk \n"); return -1; } /* Compress with clevel=5 and shuffle active */ csize = blosc2_compress_ctx(cctx, data_in, chunksize, data_out, chunksize + BLOSC_MAX_OVERHEAD); if (csize == 0) { printf("Buffer is uncompressible. Giving up.\n"); return 0; } else if (csize < 0) { printf("Compression error. Error code: %" PRId64 "\n", csize); return (int) csize; } csize_f += csize; /* Decompress */ dsize = blosc2_decompress_ctx(dctx, data_out, chunksize + BLOSC_MAX_OVERHEAD, data_dest, chunksize); if (dsize <= 0) { printf("Decompression error. Error code: %" PRId64 "\n", dsize); return (int) dsize; } } csize_f = csize_f / nchunks; free(data_in); free(data_out); free(data_dest); blosc2_free_ctx(cctx); blosc2_free_ctx(dctx); printf("Succesful roundtrip!\n"); printf("Compression: %d -> %" PRId64 " (%.1fx)\n", chunksize, csize_f, (1. * chunksize) / (double) csize_f); return (int) (chunksize - csize_f); } int float_cyclic() { blosc2_schunk *schunk = blosc2_schunk_open("example_float_cyclic.caterva"); /* Run the test. */ int result = test_zfp_rate_float(schunk); blosc2_schunk_free(schunk); return result; } int double_same_cells() { blosc2_schunk *schunk = blosc2_schunk_open("example_double_same_cells.caterva"); /* Run the test. */ int result = test_zfp_rate_double(schunk); blosc2_schunk_free(schunk); return result; } int day_month_temp() { blosc2_schunk *schunk = blosc2_schunk_open("example_day_month_temp.caterva"); /* Run the test. */ int result = test_zfp_rate_float(schunk); blosc2_schunk_free(schunk); return result; } int item_prices() { blosc2_schunk *schunk = blosc2_schunk_open("example_item_prices.caterva"); /* Run the test. */ int result = test_zfp_rate_float(schunk); blosc2_schunk_free(schunk); return result; } int main(void) { int result; blosc_init(); // this is mandatory for initiallizing the plugin mechanism result = float_cyclic(); printf("float_cyclic: %d obtained \n \n", result); result = double_same_cells(); printf("double_same_cells: %d obtained \n \n", result); result = day_month_temp(); printf("day_month_temp: %d obtained \n \n", result); result = item_prices(); printf("item_prices: %d obtained \n \n", result); blosc_destroy(); return BLOSC2_ERROR_SUCCESS; }
clayne/c-blosc2
tests/fuzz/fuzz_compress_chunk.c
<gh_stars>0 #include <stdint.h> #include <stdlib.h> #include <blosc2.h> #ifdef __cplusplus extern "C" { #endif int LLVMFuzzerTestOneInput(const uint8_t *data, int32_t size) { const char *compressors[] = { "blosclz", "lz4", "lz4hc", "zlib", "zstd" }; int num_comp = sizeof(compressors) / sizeof(char*); int level = 9, filter = BLOSC_BITSHUFFLE, cindex = 0, i = 0; size_t nbytes, cbytes, blocksize; void *output, *input; blosc_set_nthreads(1); if (size > 0) level = data[0] % (9 + 1); if (size > 1) filter = data[1] % (BLOSC_BITSHUFFLE + 1); if (size > 2) cindex = data[2]; /* Find next available compressor */ while (blosc_set_compressor(compressors[cindex % num_comp]) == -1 && i < num_comp) { cindex++, i++; } if (i == num_comp) { /* No compressors available */ return 0; } if (size > 3 && data[3] % 7 == 0) blosc_set_blocksize(4096); output = malloc(size + 1); if (output == NULL) return 0; if (blosc2_compress(level, filter, 1, data, size, output, size) == 0) { /* Cannot compress src buffer into dest */ free(output); return 0; } blosc_cbuffer_sizes(output, &nbytes, &cbytes, &blocksize); /* Don't allow address sanitizer to allocate more than INT32_MAX */ if (cbytes >= INT32_MAX) { free(output); return 0; } input = malloc(cbytes); if (input != NULL) { blosc_decompress(output, input, cbytes); free(input); } free(output); return 0; } #ifdef __cplusplus } #endif
clayne/c-blosc2
blosc/blosc2-stdio.c
<filename>blosc/blosc2-stdio.c /********************************************************************* Blosc - Blocked Shuffling and Compression Library Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ #include "blosc2/blosc2-stdio.h" #include "blosc2.h" void *blosc2_stdio_open(const char *urlpath, const char *mode, void *params) { BLOSC_UNUSED_PARAM(params); FILE *file = fopen(urlpath, mode); if (file == NULL) return NULL; blosc2_stdio_file *my_fp = malloc(sizeof(blosc2_stdio_file)); my_fp->file = file; return my_fp; } int blosc2_stdio_close(void *stream) { blosc2_stdio_file *my_fp = (blosc2_stdio_file *) stream; int err = fclose(my_fp->file); free(my_fp); return err; } int64_t blosc2_stdio_tell(void *stream) { blosc2_stdio_file *my_fp = (blosc2_stdio_file *) stream; int64_t pos; #if defined(_MSC_VER) && (_MSC_VER >= 1400) pos = _ftelli64(my_fp->file); #else pos = (int64_t)ftell(my_fp->file); #endif return pos; } int blosc2_stdio_seek(void *stream, int64_t offset, int whence) { blosc2_stdio_file *my_fp = (blosc2_stdio_file *) stream; int rc; #if defined(_MSC_VER) && (_MSC_VER >= 1400) rc = _fseeki64(my_fp->file, offset, whence); #else rc = fseek(my_fp->file, (long) offset, whence); #endif return rc; } int64_t blosc2_stdio_write(const void *ptr, int64_t size, int64_t nitems, void *stream) { blosc2_stdio_file *my_fp = (blosc2_stdio_file *) stream; size_t nitems_ = fwrite(ptr, (size_t) size, (size_t) nitems, my_fp->file); return (int64_t) nitems_; } int64_t blosc2_stdio_read(void *ptr, int64_t size, int64_t nitems, void *stream) { blosc2_stdio_file *my_fp = (blosc2_stdio_file *) stream; size_t nitems_ = fread(ptr, (size_t) size, (size_t) nitems, my_fp->file); return (int64_t) nitems_; } int blosc2_stdio_truncate(void *stream, int64_t size) { blosc2_stdio_file *my_fp = (blosc2_stdio_file *) stream; int rc; #if defined(_MSC_VER) && (_MSC_VER >= 1400) rc = _chsize_s(_fileno(my_fp->file), size); #else rc = ftruncate(fileno(my_fp->file), size); #endif return rc; }
clayne/c-blosc2
contrib/shuffle_neon/shuffle8_neon/shuffle8_neon_opt.c
/* Routine for shuffling a buffer for a type size of 8 bytes. First version (non-optimized) */ void shuffle8_neon(uint8_t* const dest, const uint8_t* const src, const size_t vectorizable_elements, const size_t total_elements) { size_t i, j, k, l; static const size_t bytesoftype = 8; uint8x8x4_t r0[2], r1[2]; uint8_t *index = "\x00\x08\x10\x18\x01\x09\x11\x19" "\x02\x0a\x12\x1a\x03\x0b\x13\x1b" "\x04\x0c\x14\x1c\x05\x0d\x15\x1d" "\x06\x0e\x16\x1e\x07\x0f\x17\x1f"; uint8_t *index_top = "\x00\x01\x02\x03\xff\xff\xff\xff" "\x04\x05\x06\x07\xff\xff\xff\xff" "\x08\x09\x0a\x0b\xff\xff\xff\xff" "\x0c\x0d\x0e\x0f\xff\xff\xff\xff" "\x10\x11\x12\x13\xff\xff\xff\xff" "\x14\x15\x16\x17\xff\xff\xff\xff" "\x18\x19\x1a\x1b\xff\xff\xff\xff" "\x1c\x1d\x1e\x1f\xff\xff\xff\xff"; uint8_t *index_bottom = "\xff\xff\xff\xff\x00\x01\x02\x03" "\xff\xff\xff\xff\x04\x05\x06\x07" "\xff\xff\xff\xff\x08\x09\x0a\x0b" "\xff\xff\xff\xff\x0c\x0d\x0e\x0f" "\xff\xff\xff\xff\x10\x11\x12\x13" "\xff\xff\xff\xff\x14\x15\x16\x17" "\xff\xff\xff\xff\x18\x19\x1a\x1b" "\xff\xff\xff\xff\x1c\x1d\x1e\x1f"; for(i = 0, k = 0; i < vectorizable_elements*bytesoftype; i += 64, k++) { /* Load 8 byte groups to the structures */ for(j = 0; j < 4; j++) { for (l = 0; l < 2; l++) { r0[l].val[j] = vld1_u8(src + l*32 + k*32 + k*sizeof(r0[l]) + j*sizeof(r0[l].val[j])); } } /* Table look up to separate bytes */ for(j = 0; j < 4; j++) { for (l = 0; l < 2; l++) { r1[l].val[j] = vtbl4_u8(r0[l], vld1_u8(index + j*sizeof(r1[l].val[j]))); } } /* Rearrange the distribution of the structures */ for(j = 0; j < 4; j++) { r0[0].val[j] = vtbx4_u8(r0[0].val[j], r1[0], vld1_u8(index_top + j*sizeof(r0[0].val[j]))); r0[0].val[j] = vtbx4_u8(r0[0].val[j], r1[1], vld1_u8(index_bottom + j*sizeof(r0[0].val[j]))); r0[1].val[j] = vtbx4_u8(r0[1].val[j], r1[0], vld1_u8(index_top + 32 + j*sizeof(r0[1].val[j]))); r0[1].val[j] = vtbx4_u8(r0[1].val[j], r1[1], vld1_u8(index_bottom + 32 + j*sizeof(r0[1].val[j]))); } /* Store the results in the destination vector */ for(j = 0; j < 4; j++) { for (l = 0; l < 2; l++) { vst1_u8(dest + total_elements*(j+l*4) + k*sizeof(r0[l].val[j]), r0[l].val[j]); } } } }
clayne/c-blosc2
blosc/frame.h
<gh_stars>0 /********************************************************************* Blosc - Blocked Shuffling and Compression Library Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ #ifndef BLOSC_FRAME_H #define BLOSC_FRAME_H #include <stdio.h> #include <stdint.h> // Different types of frames #define FRAME_CONTIGUOUS_TYPE 0 #define FRAME_DIRECTORY_TYPE 1 // Constants for metadata placement in header #define FRAME_HEADER_MAGIC 2 #define FRAME_HEADER_LEN (FRAME_HEADER_MAGIC + 8 + 1) // 11 #define FRAME_LEN (FRAME_HEADER_LEN + 4 + 1) // 16 #define FRAME_FLAGS (FRAME_LEN + 8 + 1) // 25 #define FRAME_TYPE (FRAME_FLAGS + 1) // 26 #define FRAME_CODECS (FRAME_FLAGS + 2) // 27 #define FRAME_NBYTES (FRAME_FLAGS + 4 + 1) // 30 #define FRAME_CBYTES (FRAME_NBYTES + 8 + 1) // 39 #define FRAME_TYPESIZE (FRAME_CBYTES + 8 + 1) // 48 #define FRAME_BLOCKSIZE (FRAME_TYPESIZE + 4 + 1) // 53 #define FRAME_CHUNKSIZE (FRAME_BLOCKSIZE + 4 + 1) // 58 #define FRAME_NTHREADS_C (FRAME_CHUNKSIZE + 4 + 1) // 63 #define FRAME_NTHREADS_D (FRAME_NTHREADS_C + 2 + 1) // 66 #define FRAME_HAS_VLMETALAYERS (FRAME_NTHREADS_D + 2) // 68 #define FRAME_FILTER_PIPELINE (FRAME_HAS_VLMETALAYERS + 1 + 1) // 70 #define FRAME_UDCODEC (FRAME_FILTER_PIPELINE + 1 + 6) // 77 #define FRAME_CODEC_META (FRAME_FILTER_PIPELINE + 1 + 7) // 78 #define FRAME_HEADER_MINLEN (FRAME_FILTER_PIPELINE + 1 + 16) // 87 <- minimum length #define FRAME_METALAYERS (FRAME_HEADER_MINLEN) // 87 #define FRAME_IDX_SIZE (FRAME_METALAYERS + 1 + 1) // 89 #define FRAME_FILTER_PIPELINE_MAX (8) // the maximum number of filters that can be stored in header #define FRAME_TRAILER_VERSION_BETA2 (0U) // for beta.2 and former #define FRAME_TRAILER_VERSION (1U) // can be up to 127 #define FRAME_TRAILER_MINLEN (25) // minimum length for the trailer (msgpack overhead) #define FRAME_TRAILER_LEN_OFFSET (22) // offset to trailer length (counting from the end) #define FRAME_TRAILER_VLMETALAYERS (2) typedef struct { char* urlpath; //!< The name of the file or directory if it's an sframe; if NULL, this is in-memory uint8_t* cframe; //!< The in-memory, contiguous frame buffer bool avoid_cframe_free; //!< Whether the cframe can be freed (false) or not (true). uint8_t* coffsets; //!< Pointers to the (compressed, on-disk) chunk offsets int64_t len; //!< The current length of the frame in (compressed) bytes int64_t maxlen; //!< The maximum length of the frame; if 0, there is no maximum uint32_t trailer_len; //!< The current length of the trailer in (compressed) bytes bool sframe; //!< Whether the frame is sparse (true) or not blosc2_schunk *schunk; //!< The schunk associated } blosc2_frame_s; /********************************************************************* Frame struct related functions. These are rather low-level and the blosc2_schunk interface is recommended instead. *********************************************************************/ /** * @brief Create a new frame. * * @param urlpath The filename of the frame. If not persistent, pass NULL. * * @return The new frame. */ blosc2_frame_s* frame_new(const char* urlpath); /** * @brief Create a frame from a super-chunk. * * @param schunk The super-chunk from where the frame will be created. * @param frame The pointer for the frame that will be populated. * * @note If frame->urlpath is NULL, a frame is created in-memory; else it is created * on-disk. * * @return The size in bytes of the frame. If an error occurs it returns a negative value. */ int64_t frame_from_schunk(blosc2_schunk* schunk, blosc2_frame_s* frame); /** * @brief Free all memory from a frame. * * @param frame The frame to be freed. * * @return 0 if succeeds. */ int frame_free(blosc2_frame_s *frame); /** * @brief Initialize a frame out of a file. * * @param urlpath The file name. * * @return The frame created from the file. */ blosc2_frame_s* frame_from_file(const char *urlpath, const blosc2_io *io_cb); /** * @brief Initialize a frame out of a frame buffer. * * @param buffer The buffer for the frame. * @param len The length of buffer for the frame. * @param copy Whether the frame buffer should be copied internally or not. * * @return The frame created from the frame buffer. */ blosc2_frame_s* frame_from_cframe(uint8_t *cframe, int64_t len, bool copy); /** * @brief Create a super-chunk from a frame. * * @param frame The frame from which the super-chunk will be created. * @param copy If true, a new frame buffer is created * internally to serve as storage for the super-chunk. Else, the * super-chunk will be backed by @p frame (i.e. no copies are made). * * @return The super-chunk corresponding to the frame. */ blosc2_schunk* frame_to_schunk(blosc2_frame_s* frame, bool copy, const blosc2_io *udio); blosc2_storage * get_new_storage(const blosc2_storage *storage, const blosc2_cparams *cdefaults, const blosc2_dparams *ddefaults, const blosc2_io *iodefaults); void* frame_append_chunk(blosc2_frame_s* frame, void* chunk, blosc2_schunk* schunk); void* frame_insert_chunk(blosc2_frame_s* frame, int64_t nchunk, void* chunk, blosc2_schunk* schunk); void* frame_update_chunk(blosc2_frame_s* frame, int64_t nchunk, void* chunk, blosc2_schunk* schunk); void* frame_delete_chunk(blosc2_frame_s* frame, int64_t nchunk, blosc2_schunk* schunk); int frame_reorder_offsets(blosc2_frame_s *frame, const int64_t *offsets_order, blosc2_schunk* schunk); int frame_get_chunk(blosc2_frame_s* frame, int64_t nchunk, uint8_t **chunk, bool *needs_free); int frame_get_lazychunk(blosc2_frame_s* frame, int64_t nchunk, uint8_t **chunk, bool *needs_free); int frame_decompress_chunk(blosc2_context* dctx, blosc2_frame_s* frame, int64_t nchunk, void *dest, int32_t nbytes); int frame_update_header(blosc2_frame_s* frame, blosc2_schunk* schunk, bool new); int frame_update_trailer(blosc2_frame_s* frame, blosc2_schunk* schunk); int64_t frame_fill_special(blosc2_frame_s* frame, int64_t nitems, int special_value, int32_t chunksize, blosc2_schunk* schunk); #endif //BLOSC_FRAME_H
clayne/c-blosc2
blosc/delta.c
/********************************************************************* Blosc - Blocked Shuffling and Compression Library Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ #include <stdio.h> #include "delta.h" /* Apply the delta filters to src. This can never fail. */ void delta_encoder(const uint8_t* dref, int32_t offset, int32_t nbytes, int32_t typesize, const uint8_t* src, uint8_t* dest) { int32_t i; if (offset == 0) { /* This is the reference block, use delta coding in elements */ switch (typesize) { case 1: dest[0] = dref[0]; for (i = 1; i < nbytes; i++) { dest[i] = src[i] ^ dref[i-1]; } break; case 2: ((uint16_t *)dest)[0] = ((uint16_t *)dref)[0]; for (i = 1; i < nbytes / 2; i++) { ((uint16_t *)dest)[i] = ((uint16_t *)src)[i] ^ ((uint16_t *)dref)[i-1]; } break; case 4: ((uint32_t *)dest)[0] = ((uint32_t *)dref)[0]; for (i = 1; i < nbytes / 4; i++) { ((uint32_t *)dest)[i] = ((uint32_t *)src)[i] ^ ((uint32_t *)dref)[i-1]; } break; case 8: ((uint64_t *)dest)[0] = ((uint64_t *)dref)[0]; for (i = 1; i < nbytes / 8; i++) { ((uint64_t *)dest)[i] = ((uint64_t *)src)[i] ^ ((uint64_t *)dref)[i-1]; } break; default: if ((typesize % 8) == 0) { delta_encoder(dref, offset, nbytes, 8, src, dest); } else { delta_encoder(dref, offset, nbytes, 1, src, dest); } } } else { /* Use delta coding wrt reference block */ switch (typesize) { case 1: for (i = 0; i < nbytes; i++) { dest[i] = src[i] ^ dref[i]; } break; case 2: for (i = 0; i < nbytes / 2; i++) { ((uint16_t *) dest)[i] = ((uint16_t *) src)[i] ^ ((uint16_t *) dref)[i]; } break; case 4: for (i = 0; i < nbytes / 4; i++) { ((uint32_t *) dest)[i] = ((uint32_t *) src)[i] ^ ((uint32_t *) dref)[i]; } break; case 8: for (i = 0; i < nbytes / 8; i++) { ((uint64_t *) dest)[i] = ((uint64_t *) src)[i] ^ ((uint64_t *) dref)[i]; } break; default: if ((typesize % 8) == 0) { delta_encoder(dref, offset, nbytes, 8, src, dest); } else { delta_encoder(dref, offset, nbytes, 1, src, dest); } } } } /* Undo the delta filter in dest. This can never fail. */ void delta_decoder(const uint8_t* dref, int32_t offset, int32_t nbytes, int32_t typesize, uint8_t* dest) { int32_t i; if (offset == 0) { /* Decode delta for the reference block */ switch (typesize) { case 1: for (i = 1; i < nbytes; i++) { dest[i] ^= dref[i-1]; } break; case 2: for (i = 1; i < nbytes / 2; i++) { ((uint16_t *)dest)[i] ^= ((uint16_t *)dref)[i-1]; } break; case 4: for (i = 1; i < nbytes / 4; i++) { ((uint32_t *)dest)[i] ^= ((uint32_t *)dref)[i-1]; } break; case 8: for (i = 1; i < nbytes / 8; i++) { ((uint64_t *)dest)[i] ^= ((uint64_t *)dref)[i-1]; } break; default: if ((typesize % 8) == 0) { delta_decoder(dref, offset, nbytes, 8, dest); } else { delta_decoder(dref, offset, nbytes, 1, dest); } } } else { /* Decode delta for the non-reference blocks */ switch (typesize) { case 1: for (i = 0; i < nbytes; i++) { dest[i] ^= dref[i]; } break; case 2: for (i = 0; i < nbytes / 2; i++) { ((uint16_t *)dest)[i] ^= ((uint16_t *)dref)[i]; } break; case 4: for (i = 0; i < nbytes / 4; i++) { ((uint32_t *)dest)[i] ^= ((uint32_t *)dref)[i]; } break; case 8: for (i = 0; i < nbytes / 8; i++) { ((uint64_t *)dest)[i] ^= ((uint64_t *)dref)[i]; } break; default: if ((typesize % 8) == 0) { delta_decoder(dref, offset, nbytes, 8, dest); } else { delta_decoder(dref, offset, nbytes, 1, dest); } } } }
clayne/c-blosc2
tests/test_prefilter.c
<filename>tests/test_prefilter.c /* Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) */ #include "test_common.h" int tests_run = 0; #define SIZE (500 * 1000) #define NTHREADS 2 typedef struct { int ninputs; uint8_t *inputs[2]; int32_t input_typesizes[2]; } test_preparams; // Global vars blosc2_cparams cparams; blosc2_dparams dparams; blosc2_context *cctx, *dctx; static int32_t data[SIZE]; static int32_t data2[SIZE]; static int32_t data_out[SIZE + BLOSC_MAX_OVERHEAD / sizeof(int32_t)]; static int32_t data_dest[SIZE]; int32_t isize = SIZE * sizeof(int32_t); int32_t osize = SIZE * sizeof(int32_t) + BLOSC_MAX_OVERHEAD; int dsize = SIZE * sizeof(int32_t); int csize; int prefilter_func(blosc2_prefilter_params *preparams) { test_preparams *tpreparams = preparams->user_data; int nelems = preparams->out_size / preparams->out_typesize; if (tpreparams->ninputs == 0) { int32_t *input0 = (int32_t *)preparams->in; for (int i = 0; i < nelems; i++) { ((int32_t*)(preparams->out))[i] = input0[i] * 2; } } else if (tpreparams->ninputs == 1) { int32_t *input0 = ((int32_t *)(tpreparams->inputs[0] + preparams->out_offset)); for (int i = 0; i < nelems; i++) { ((int32_t*)(preparams->out))[i] = input0[i] * 3; } } else if (tpreparams->ninputs == 2) { int32_t *input0 = ((int32_t *)(tpreparams->inputs[0] + preparams->out_offset)); int32_t *input1 = ((int32_t *)(tpreparams->inputs[1] + preparams->out_offset)); for (int i = 0; i < nelems; i++) { ((int32_t *) (preparams->out))[i] = input0[i] + input1[i]; } } else { return 1; } return 0; } static char *test_prefilter0(void) { // Set some prefilter parameters and function cparams.prefilter = (blosc2_prefilter_fn)prefilter_func; // We need to zero the contents of the preparams. TODO: make a constructor for ppreparams. blosc2_prefilter_params preparams = {0}; test_preparams tpreparams = {0}; preparams.user_data = (void*)&tpreparams; cparams.preparams = &preparams; cctx = blosc2_create_cctx(cparams); csize = blosc2_compress_ctx(cctx, data, isize, data_out, osize); mu_assert("Compression error", csize > 0); /* Create a context for decompression */ dctx = blosc2_create_dctx(dparams); /* Decompress */ dsize = blosc2_decompress_ctx(dctx, data_out, csize, data_dest, dsize); mu_assert("Decompression error", dsize >= 0); for (int i = 0; i < SIZE; i++) { mu_assert("Decompressed data differs from original!", data[i] * 2 == data_dest[i]); } /* Free resources */ blosc2_free_ctx(cctx); blosc2_free_ctx(dctx); return 0; } static char *test_prefilter1(void) { // Set some prefilter parameters and function cparams.prefilter = (blosc2_prefilter_fn)prefilter_func; // We need to zero the contents of the preparams. TODO: make a constructor for ppreparams. blosc2_prefilter_params preparams = {0}; test_preparams tpreparams = {0}; tpreparams.ninputs = 1; tpreparams.inputs[0] = (uint8_t*)data; tpreparams.input_typesizes[0] = cparams.typesize; preparams.user_data = (void*)&tpreparams; cparams.preparams = &preparams; cctx = blosc2_create_cctx(cparams); csize = blosc2_compress_ctx(cctx, data, isize, data_out, osize); mu_assert("Compression error", csize > 0); /* Create a context for decompression */ dctx = blosc2_create_dctx(dparams); /* Decompress */ dsize = blosc2_decompress_ctx(dctx, data_out, csize, data_dest, dsize); mu_assert("Decompression error", dsize >= 0); for (int i = 0; i < SIZE; i++) { mu_assert("Decompressed data differs from original!", data[i] * 3 == data_dest[i]); } /* Free resources */ blosc2_free_ctx(cctx); blosc2_free_ctx(dctx); return 0; } static char *test_prefilter2(void) { // Set some prefilter parameters and function cparams.prefilter = (blosc2_prefilter_fn)prefilter_func; // We need to zero the contents of the preparams. TODO: make a constructor for ppreparams. blosc2_prefilter_params preparams = {0}; test_preparams tpreparams = {0}; tpreparams.ninputs = 2; tpreparams.inputs[0] = (uint8_t*)data; tpreparams.inputs[1] = (uint8_t*)data2; tpreparams.input_typesizes[0] = cparams.typesize; tpreparams.input_typesizes[1] = cparams.typesize; preparams.user_data = (void*)&tpreparams; cparams.preparams = &preparams; cctx = blosc2_create_cctx(cparams); csize = blosc2_compress_ctx(cctx, data, isize, data_out, osize); mu_assert("Buffer is uncompressible", csize != 0); mu_assert("Compression error", csize > 0); /* Create a context for decompression */ dctx = blosc2_create_dctx(dparams); /* Decompress */ dsize = blosc2_decompress_ctx(dctx, data_out, csize, data_dest, dsize); mu_assert("Decompression error", dsize >= 0); for (int i = 0; i < SIZE; i++) { if ((data[i] + data2[i]) != data_dest[i]) { printf("Error in pos '%d': (%d + %d) != %d\n", i, data[i], data2[i], data_dest[i]); } mu_assert("Decompressed data differs from original!", (data[i] + data2[i]) == data_dest[i]); } /* Free resources */ blosc2_free_ctx(cctx); blosc2_free_ctx(dctx); return 0; } static char *all_tests(void) { // Check with an assortment of clevels and nthreads cparams.clevel = 0; cparams.nthreads = 1; dparams.nthreads = NTHREADS; mu_run_test(test_prefilter0); cparams.clevel = 1; cparams.nthreads = 1; mu_run_test(test_prefilter0); cparams.clevel = 7; cparams.nthreads = NTHREADS; mu_run_test(test_prefilter0); cparams.clevel = 9; cparams.nthreads = NTHREADS; dparams.nthreads = NTHREADS; mu_run_test(test_prefilter0); cparams.clevel = 0; cparams.nthreads = 1; dparams.nthreads = NTHREADS; mu_run_test(test_prefilter1); cparams.clevel = 1; cparams.nthreads = 1; mu_run_test(test_prefilter1); cparams.clevel = 7; cparams.nthreads = NTHREADS; mu_run_test(test_prefilter1); cparams.clevel = 0; cparams.nthreads = NTHREADS; dparams.nthreads = 1; mu_run_test(test_prefilter2); cparams.clevel = 5; cparams.nthreads = 1; mu_run_test(test_prefilter2); cparams.clevel = 9; cparams.nthreads = NTHREADS; mu_run_test(test_prefilter2); return 0; } int main(void) { /* Initialize inputs */ for (int i = 0; i < SIZE; i++) { data[i] = i; data2[i] = i * 2; } install_blosc_callback_test(); /* optionally install callback test */ /* Create a context for compression */ cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.typesize = sizeof(int32_t); cparams.compcode = BLOSC_BLOSCLZ; cparams.filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_SHUFFLE; dparams = BLOSC2_DPARAMS_DEFAULTS; /* Run all the suite */ char* result = all_tests(); if (result != 0) { printf(" (%s)\n", result); } else { printf(" ALL TESTS PASSED"); } printf("\tTests run: %d\n", tests_run); return result != 0; }
clayne/c-blosc2
contrib/shuffle_neon/shuffle8_neon/shuffle8_neon_vtbx.c
/* Routine for shuffling a buffer for a type size of 8 bytes. Second version (non-optimized) */ void shuffle8_neon(uint8_t* const dest, const uint8_t* const src, const size_t vectorizable_elements, const size_t total_elements) { size_t i, j, k, l; static const size_t bytesoftype = 8; uint8x8x4_t r0[2], r1[2]; uint8_t *index = "\x00\x02\x04\x06\xff\xff\xff\xff" "\x08\x0a\x0c\x0e\xff\xff\xff\xff" "\x10\x12\x14\x16\xff\xff\xff\xff" "\x18\x1a\x1c\x1e\xff\xff\xff\xff" "\xff\xff\xff\xff\x00\x02\x04\x06" "\xff\xff\xff\xff\x08\x0a\x0c\x0e" "\xff\xff\xff\xff\x10\x12\x14\x16" "\xff\xff\xff\xff\x18\x1a\x1c\x1e" "\x01\x03\x05\x07\xff\xff\xff\xff" "\x09\x0b\x0d\x0f\xff\xff\xff\xff" "\x11\x13\x15\x17\xff\xff\xff\xff" "\x19\x1b\x1d\x1f\xff\xff\xff\xff" "\xff\xff\xff\xff\x01\x03\x05\x07" "\xff\xff\xff\xff\x09\x0b\x0d\x0f" "\xff\xff\xff\xff\x11\x13\x15\x17" "\xff\xff\xff\xff\x19\x1b\x1d\x1f"; for(i = 0, k = 0; i < vectorizable_elements*bytesoftype; i += 64, k++) { /* Load (and permute) 64 bytes to the structure r0*/ for (j = 0; j < 2; j++) { r0[j] = vld4_u8(src + i + j*32); } /* Extended table look up to to rearrange bytes */ for(j = 0; j < 4; j++) { r1[0].val[j] = vtbx4_u8(r1[0].val[j], r0[0], vld1_u8(index + j*8)); r1[0].val[j] = vtbx4_u8(r1[0].val[j], r0[1], vld1_u8(index + 32 + j*8)); r1[1].val[j] = vtbx4_u8(r1[1].val[j], r0[0], vld1_u8(index + 64 + j*8)); r1[1].val[j] = vtbx4_u8(r1[1].val[j], r0[1], vld1_u8(index + 96 + j*8)); } /* Store the results in the destination vector */ for(j = 0; j < 4; j++) { for (l = 0; l < 2; l++) { vst1_u8(dest + total_elements*(j+l*4) + k*8, r1[l].val[j]); } } } }
clayne/c-blosc2
contrib/shuffle_neon/shuffle8_neon/shuffle8_neon_bucle.c
<filename>contrib/shuffle_neon/shuffle8_neon/shuffle8_neon_bucle.c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <arm_neon.h> #include <string.h> static void printmem8(uint8x8_t buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x\n", buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem16(uint8x16_t r0) { uint8_t buf[16]; ((uint8x16_t *)buf)[0] = r0; printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem16x4(uint16x4_t buf) { printf("%x,%x,%x,%x\n", buf[3], buf[2], buf[1], buf[0]); } static void printmem(uint8_t* buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x," "%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[31], buf[30], buf[29], buf[28], buf[27], buf[26], buf[25], buf[24], buf[23], buf[22], buf[21], buf[20], buf[19], buf[18], buf[17], buf[16], buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } /* Routine optimized for shuffling a buffer for a type size of 8 bytes. */ void shuffle8_neon(uint8_t* const dest, const uint8_t* const src, const size_t vectorizable_elements, const size_t total_elements) { size_t i, j, k; static const size_t bytesoftype = 8; uint8x8x2_t r0[4]; uint16x4x2_t r1[4]; uint32x2x2_t r2[4]; for(i = 0, k = 0; i < vectorizable_elements*bytesoftype; i += 64, k++) { /* Load and interleave groups of 8 bytes (64 bytes) to the structure r0*/ for (j = 0; j < 4; j++) { r0[j] = vzip_u8(vld1_u8(src + i + (2*j)*8), vld1_u8(src + i +(2*j+1)*8)); } /* Interleave 16 bytes*/ r1[0] = vzip_u16(vreinterpret_u16_u8(r0[0].val[0]), vreinterpret_u16_u8(r0[1].val[0])); r1[1] = vzip_u16(vreinterpret_u16_u8(r0[0].val[1]), vreinterpret_u16_u8(r0[1].val[1])); r1[2] = vzip_u16(vreinterpret_u16_u8(r0[2].val[0]), vreinterpret_u16_u8(r0[3].val[0])); r1[3] = vzip_u16(vreinterpret_u16_u8(r0[2].val[1]), vreinterpret_u16_u8(r0[3].val[1])); /* Interleave 32 bytes */ r2[0] = vzip_u32(vreinterpret_u32_u16(r1[0].val[0]), vreinterpret_u32_u16(r1[2].val[0])); r2[1] = vzip_u32(vreinterpret_u32_u16(r1[0].val[1]), vreinterpret_u32_u16(r1[2].val[1])); r2[2] = vzip_u32(vreinterpret_u32_u16(r1[1].val[0]), vreinterpret_u32_u16(r1[3].val[0])); r2[3] = vzip_u32(vreinterpret_u32_u16(r1[1].val[1]), vreinterpret_u32_u16(r1[3].val[1])); /* Store the results in the destination vector */ for (j = 0; j < 4; j++) { vst1_u8(dest + k*8 + (j*2)*total_elements, vreinterpret_u8_u32(r2[j].val[0])); vst1_u8(dest + k*8 + (j*2+1)*total_elements, vreinterpret_u8_u32(r2[j].val[1])); } } } void main() { uint8_t *src = "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\x13\x21\x17\xc8\xc9\x34\x25\x11\x67\x74\x4e\xe8\x67\x74\x4e\xe8" "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\x13\x21\x17\xc8\xc9\x34\x25\x11\x67\x74\x4e\xe8\x67\x74\x4e\xe8"; uint8_t *dest = calloc(288,2); size_t vectorizable_elements = 32; size_t total_elements = 36; shuffle8_neon(dest, src, vectorizable_elements, total_elements); printf("vst1q_u8 \n"); printmem(dest); printmem(dest+32); printmem(dest+64); printmem(dest+96); printmem(dest+128); printmem(dest+160); printmem(dest+192); printmem(dest+224); printmem(dest+256); free(dest); }
clayne/c-blosc2
tests/test_getitem_delta.c
<gh_stars>0 /* Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include "test_common.h" int tests_run = 0; static char* test_getitem(void) { blosc_set_nthreads(1); size_t type_size = 131; size_t num_elements = 1; blosc_set_compressor("blosclz"); blosc_set_delta(1); size_t buffer_size = type_size * num_elements; /* Allocate memory for the test. */ void* original = malloc(buffer_size); void* intermediate = malloc(buffer_size + BLOSC_MAX_OVERHEAD); void* items = malloc(buffer_size); void* result = malloc(buffer_size); /* The test data */ memset(original, 0, buffer_size); ((char*)original)[128] = 1; /* Compress the input data and store it in an intermediate buffer. Decompress the data from the intermediate buffer into a result buffer. */ blosc_compress(1, 0, type_size, buffer_size, original, intermediate, buffer_size + BLOSC_MAX_OVERHEAD); int start_item = 0; int num_items = 1; blosc_decompress(intermediate, result, buffer_size); assert(memcmp(original, result, buffer_size) == 0); mu_assert("ERROR: decompression with delta filter fails", memcmp(original, result, buffer_size) == 0); /* Now that we see the round-trip passed, check the getitem */ int get_result = blosc_getitem(intermediate, start_item, num_items, items); mu_assert("ERROR: the number of items in getitem is not correct", (uint32_t) get_result == (num_items * type_size)); mu_assert("ERROR: getitem with delta filter fails", memcmp(original, items, get_result) == 0); /* Free allocated memory. */ free(original); free(intermediate); free(items); free(result); return EXIT_SUCCESS; } static char *all_tests(void) { mu_run_test(test_getitem); return EXIT_SUCCESS; } int main(void) { char *result; blosc_init(); result = all_tests(); blosc_destroy(); return result != EXIT_SUCCESS; }
clayne/c-blosc2
examples/frame_metalayers.c
<gh_stars>0 /* Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) Example program demonstrating the use of the metalayers. To compile this program: $ gcc -O frame_metalayers.c -o frame_metalayers -lblosc2 To run: $ ./frame_metalayers Blosc version info: 2.0.0a6.dev ($Date:: 2018-05-18 #$) Compression ratio: 3.8 MB -> 0.0 MB (234.4x) Compression time: 0.00218 s, 1747.2 MB/s Time for schunk -> frame: 1.19e-05 s, 313.5 GB/s Frame length in memory: 17247 bytes Frame length on disk: 17247 bytes Time for frame -> fileframe (simple_frame.b2frame): 0.000144 s, 25.9 GB/s Time for fileframe (frame_metalayers.b2frame) -> frame : 4.08e-05 s, 91.3 GB/s Time for fileframe -> schunk: 4.29e-07 s, 8683.7 GB/s */ #include <stdio.h> #include <string.h> #include <assert.h> #include <blosc2.h> #define KB 1024. #define MB (1024*KB) #define GB (1024*MB) #define CHUNKSIZE (1000 * 1000) #define NCHUNKS 1 #define NTHREADS 4 int main(void) { blosc_init(); int32_t isize = CHUNKSIZE * sizeof(int32_t); int32_t* data = malloc(isize); int64_t nbytes, cbytes; int i, nchunk; int64_t nchunks; blosc_timestamp_t last, current; double ttotal; printf("Blosc version info: %s (%s)\n", BLOSC_VERSION_STRING, BLOSC_VERSION_DATE); /* Create a super-chunk container */ blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.typesize = sizeof(int32_t); //cparams.compcode = BLOSC_LZ4; cparams.clevel = 9; cparams.nthreads = NTHREADS; blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS; dparams.nthreads = NTHREADS; blosc2_storage storage = {.cparams=&cparams, .dparams=&dparams, .contiguous=true}; blosc2_schunk* schunk = blosc2_schunk_new(&storage); // Add some metalayers (one must add metalayers prior to actual data) blosc2_meta_add(schunk, "my_metalayer1", (uint8_t *) "my_content1", (uint32_t) strlen("my_content1")); blosc2_meta_add(schunk, "my_metalayer2", (uint8_t *) "my_content1", (uint32_t) strlen("my_content1")); blosc_set_timestamp(&last); for (nchunk = 0; nchunk < NCHUNKS; nchunk++) { for (i = 0; i < CHUNKSIZE; i++) { data[i] = i * nchunk + i; } nchunks = blosc2_schunk_append_buffer(schunk, data, isize); assert(nchunks == nchunk + 1); } /* Gather some info */ nbytes = schunk->nbytes; cbytes = schunk->cbytes; blosc_set_timestamp(&current); ttotal = blosc_elapsed_secs(last, current); printf("Compression ratio: %.2f MB -> %.2f MB (%.1fx)\n", (double)nbytes / MB, (double)cbytes / MB, (1. * (double)nbytes) / (double)cbytes); printf("Compression time: %.3g s, %.1f MB/s\n", ttotal, (double)nbytes / (ttotal * MB)); blosc_set_timestamp(&last); // Update a metalayer (this is fine as long as the new content does not exceed the size of the previous one) blosc2_meta_update(schunk, "my_metalayer2", (uint8_t *) "my_content2", (uint32_t) strlen("my_content2")); blosc_set_timestamp(&current); ttotal = blosc_elapsed_secs(last, current); printf("Time for update metalayer in header: %.2g s\n", ttotal); printf("Frame length in memory: %ld bytes\n", (long)schunk->cbytes); // schunk (in-memory) -> fileframe (on-disk) blosc_set_timestamp(&last); int64_t frame_len = blosc2_schunk_to_file(schunk, "frame_metalayers.b2frame"); printf("Frame length on disk: %ld bytes\n", (long)frame_len); blosc_set_timestamp(&current); ttotal = blosc_elapsed_secs(last, current); printf("Time for frame -> fileframe (simple_frame.b2frame): %.3g s, %.1f GB/s\n", ttotal, (double)nbytes / (ttotal * GB)); // fileframe (file) -> schunk2 (schunk based on a on-disk frame) blosc_set_timestamp(&last); blosc2_schunk* schunk2 = blosc2_schunk_open("frame_metalayers.b2frame"); if (schunk2 == NULL) { printf("Cannot get the schunk from frame2"); return -1; } blosc_set_timestamp(&current); ttotal = blosc_elapsed_secs(last, current); printf("Time for fileframe (%s) -> schunk : %.3g s, %.1f GB/s\n", schunk2->storage->urlpath, ttotal, (double)nbytes / (ttotal * GB)); // Check that the metalayers had a good roundtrip if (schunk2->nmetalayers != 2) { printf("nclients not retrieved correctly!\n"); return -1; } uint8_t* content; int32_t content_len; if (blosc2_meta_get(schunk2, "my_metalayer1", &content, &content_len) < 0) { printf("metalayer not found"); return -1; } if (memcmp(content, "my_content1", content_len) != 0) { printf("serialized content for metalayer not retrieved correctly!\n"); return -1; } free(content); /* Free resources */ blosc2_schunk_free(schunk); blosc2_schunk_free(schunk2); free(data); blosc_destroy(); return 0; }
clayne/c-blosc2
plugins/codecs/ndlz/ndlz-private.h
<filename>plugins/codecs/ndlz/ndlz-private.h /********************************************************************* Blosc - Blocked Shuffling and Compression Library Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ #ifndef NDLZ_PRIVATE_H #define NDLZ_PRIVATE_H #include "context.h" #if defined (__cplusplus) extern "C" { #endif #define XXH_INLINE_ALL #define NDLZ_ERROR_NULL(pointer) \ do { \ if ((pointer) == NULL) { \ return 0; \ } \ } while (0) #if defined (__cplusplus) } #endif #endif /* NDLZ_PRIVATE_H */
clayne/c-blosc2
plugins/plugin_utils.h
/* Copyright (C) 2021 The Blosc Developers http://blosc.org License: BSD 3-Clause (see LICENSE.txt) */ void swap_store(void *dest, const void *pa, int size); int32_t deserialize_meta(uint8_t *smeta, int32_t smeta_len, int8_t *ndim, int64_t *shape, int32_t *chunkshape, int32_t *blockshape); void index_multidim_to_unidim(const int64_t *index, int8_t ndim, const int64_t *strides, int64_t *i);
clayne/c-blosc2
blosc/bitshuffle-avx2.c
<reponame>clayne/c-blosc2<gh_stars>0 /********************************************************************* Blosc - Blocked Shuffling and Compression Library Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ /********************************************************************* Bitshuffle - Filter for improving compression of typed binary data. Author: <NAME> <<EMAIL>> Website: http://www.github.com/kiyo-masui/bitshuffle Note: Adapted for c-blosc by <NAME>. See LICENSES/BITSHUFFLE.txt file for details about copyright and rights to use. **********************************************************************/ #include "bitshuffle-generic.h" #include "bitshuffle-sse2.h" #include "bitshuffle-avx2.h" /* Make sure AVX2 is available for the compilation target and compiler. */ #if !defined(__AVX2__) #error AVX2 is not supported by the target architecture/platform and/or this compiler. #endif #include <immintrin.h> /* The next is useful for debugging purposes */ #if 0 #include <stdio.h> #include <string.h> static void printymm(__m256i ymm0) { uint8_t buf[32]; ((__m256i *)buf)[0] = ymm0; printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], buf[14], buf[15], buf[16], buf[17], buf[18], buf[19], buf[20], buf[21], buf[22], buf[23], buf[24], buf[25], buf[26], buf[27], buf[28], buf[29], buf[30], buf[31]); } #endif /* ---- Code that requires AVX2. Intel Haswell (2013) and later. ---- */ /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_avx2(void* in, void* out, const size_t size, const size_t elem_size) { char* in_b = (char*)in; char* out_b = (char*)out; int32_t* out_i32; size_t nbyte = elem_size * size; int64_t count; __m256i ymm; int32_t bt; size_t ii, kk; for (ii = 0; ii + 31 < nbyte; ii += 32) { ymm = _mm256_loadu_si256((__m256i*)&in_b[ii]); for (kk = 0; kk < 8; kk++) { bt = _mm256_movemask_epi8(ymm); ymm = _mm256_slli_epi16(ymm, 1); out_i32 = (int32_t*)&out_b[((7 - kk) * nbyte + ii) / 8]; *out_i32 = bt; } } count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size, nbyte - nbyte % 32); return count; } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_avx2(void* in, void* out, const size_t size, const size_t elem_size, void* tmp_buf) { int64_t count; CHECK_MULT_EIGHT(size); count = bshuf_trans_byte_elem_sse2(in, out, size, elem_size, tmp_buf); CHECK_ERR(count); count = bshuf_trans_bit_byte_avx2(out, tmp_buf, size, elem_size); CHECK_ERR(count); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_avx2(void* in, void* out, const size_t size, const size_t elem_size) { char* in_b = (char*)in; char* out_b = (char*)out; size_t nrows = 8 * elem_size; size_t nbyte_row = size / 8; size_t ii, jj, kk, hh, mm; CHECK_MULT_EIGHT(size); if (elem_size % 4) return bshuf_trans_byte_bitrow_sse2(in, out, size, elem_size); __m256i ymm_0[8]; __m256i ymm_1[8]; __m256i ymm_storeage[8][4]; for (jj = 0; jj + 31 < nbyte_row; jj += 32) { for (ii = 0; ii + 3 < elem_size; ii += 4) { for (hh = 0; hh < 4; hh++) { for (kk = 0; kk < 8; kk++) { ymm_0[kk] = _mm256_loadu_si256((__m256i*)&in_b[ (ii * 8 + hh * 8 + kk) * nbyte_row + jj]); } for (kk = 0; kk < 4; kk++) { ymm_1[kk] = _mm256_unpacklo_epi8(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); ymm_1[kk + 4] = _mm256_unpackhi_epi8(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); } for (kk = 0; kk < 2; kk++) { for (mm = 0; mm < 2; mm++) { ymm_0[kk * 4 + mm] = _mm256_unpacklo_epi16( ymm_1[kk * 4 + mm * 2], ymm_1[kk * 4 + mm * 2 + 1]); ymm_0[kk * 4 + mm + 2] = _mm256_unpackhi_epi16( ymm_1[kk * 4 + mm * 2], ymm_1[kk * 4 + mm * 2 + 1]); } } for (kk = 0; kk < 4; kk++) { ymm_1[kk * 2] = _mm256_unpacklo_epi32(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); ymm_1[kk * 2 + 1] = _mm256_unpackhi_epi32(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); } for (kk = 0; kk < 8; kk++) { ymm_storeage[kk][hh] = ymm_1[kk]; } } for (mm = 0; mm < 8; mm++) { for (kk = 0; kk < 4; kk++) { ymm_0[kk] = ymm_storeage[mm][kk]; } ymm_1[0] = _mm256_unpacklo_epi64(ymm_0[0], ymm_0[1]); ymm_1[1] = _mm256_unpacklo_epi64(ymm_0[2], ymm_0[3]); ymm_1[2] = _mm256_unpackhi_epi64(ymm_0[0], ymm_0[1]); ymm_1[3] = _mm256_unpackhi_epi64(ymm_0[2], ymm_0[3]); ymm_0[0] = _mm256_permute2x128_si256(ymm_1[0], ymm_1[1], 32); ymm_0[1] = _mm256_permute2x128_si256(ymm_1[2], ymm_1[3], 32); ymm_0[2] = _mm256_permute2x128_si256(ymm_1[0], ymm_1[1], 49); ymm_0[3] = _mm256_permute2x128_si256(ymm_1[2], ymm_1[3], 49); _mm256_storeu_si256((__m256i*)&out_b[ (jj + mm * 2 + 0 * 16) * nrows + ii * 8], ymm_0[0]); _mm256_storeu_si256((__m256i*)&out_b[ (jj + mm * 2 + 0 * 16 + 1) * nrows + ii * 8], ymm_0[1]); _mm256_storeu_si256((__m256i*)&out_b[ (jj + mm * 2 + 1 * 16) * nrows + ii * 8], ymm_0[2]); _mm256_storeu_si256((__m256i*)&out_b[ (jj + mm * 2 + 1 * 16 + 1) * nrows + ii * 8], ymm_0[3]); } } } for (ii = 0; ii < nrows; ii++) { for (jj = nbyte_row - nbyte_row % 32; jj < nbyte_row; jj++) { out_b[jj * nrows + ii] = in_b[ii * nbyte_row + jj]; } } return (int64_t)size * (int64_t)elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_avx2(void* in, void* out, const size_t size, const size_t elem_size) { CHECK_MULT_EIGHT(size); /* With a bit of care, this could be written such that such that it is */ /* in_buf = out_buf safe. */ char* in_b = (char*)in; char* out_b = (char*)out; size_t nbyte = elem_size * size; size_t ii, jj, kk, ind; __m256i ymm; int32_t bt; if (elem_size % 4) { return bshuf_shuffle_bit_eightelem_sse2(in, out, size, elem_size); } else { for (jj = 0; jj + 31 < 8 * elem_size; jj += 32) { for (ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { ymm = _mm256_loadu_si256((__m256i*)&in_b[ii + jj]); for (kk = 0; kk < 8; kk++) { bt = _mm256_movemask_epi8(ymm); ymm = _mm256_slli_epi16(ymm, 1); ind = (ii + jj / 8 + (7 - kk) * elem_size); *(int32_t*)&out_b[ind] = bt; } } } } return (int64_t)size * (int64_t)elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_avx2(void* in, void* out, const size_t size, const size_t elem_size, void* tmp_buf) { int64_t count; CHECK_MULT_EIGHT(size); count = bshuf_trans_byte_bitrow_avx2(in, tmp_buf, size, elem_size); CHECK_ERR(count); count = bshuf_shuffle_bit_eightelem_avx2(tmp_buf, out, size, elem_size); return count; }
clayne/c-blosc2
contrib/shuffle_neon/unshuffle16_neon/unshuffle16_neon_vtbx_bucle.c
<reponame>clayne/c-blosc2<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <arm_neon.h> #include <string.h> static void printmem8(uint8x8_t buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x\n", buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem16(uint8x16_t r0) { uint8_t buf[16]; ((uint8x16_t *)buf)[0] = r0; printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem(uint8_t* buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x," "%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[31], buf[30], buf[29], buf[28], buf[27], buf[26], buf[25], buf[24], buf[23], buf[22], buf[21], buf[20], buf[19], buf[18], buf[17], buf[16], buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } void unshuffle16_neon(uint8_t* const dest, const uint8_t* const src, const size_t vectorizable_elements, const size_t total_elements) { size_t i, j, k, l; static const size_t bytesoftype = 16; uint8x8x4_t r0[4], r1[4]; uint8_t *index1_top = "\x00\x01\x02\x03\x08\x09\x0a\x0b" "\x10\x11\x12\x13\x18\x19\x1a\x1b" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\x00\x01\x02\x03\x08\x09\x0a\x0b" "\x10\x11\x12\x13\x18\x19\x1a\x1b"; uint8_t *index1_bottom = "\x04\x05\x06\x07\x0c\x0d\x0e\x0f" "\x14\x15\x16\x17\x1c\x1d\x1e\x1f" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\x04\x05\x06\x07\x0c\x0d\x0e\x0f" "\x14\x15\x16\x17\x1c\x1d\x1e\x1f"; uint8_t *index2_top = "\x00\x10\xff\xff\x04\x14\xff\xff" "\x08\x18\xff\xff\x0c\x1c\xff\xff" "\x01\x11\xff\xff\x05\x15\xff\xff" "\x09\x19\xff\xff\x0d\x1d\xff\xff" "\xff\xff\x00\x10\xff\xff\x04\x14" "\xff\xff\x08\x18\xff\xff\x0c\x1c" "\xff\xff\x01\x11\xff\xff\x05\x15" "\xff\xff\x09\x19\xff\xff\x0d\x1d"; uint8_t *index2_bottom = "\x02\x12\xff\xff\x06\x16\xff\xff" "\x0a\x1a\xff\xff\x0e\x1e\xff\xff" "\x03\x13\xff\xff\x07\x17\xff\xff" "\x0b\x1b\xff\xff\x0f\x1f\xff\xff" "\xff\xff\x02\x12\xff\xff\x06\x16" "\xff\xff\x0a\x1a\xff\xff\x0e\x1e" "\xff\xff\x03\x13\xff\xff\x07\x17" "\xff\xff\x0b\x1b\xff\xff\x0f\x1f"; for(i = 0, k = 0; i < vectorizable_elements*bytesoftype; i += 128, k++) { /* Load 16 gorups of 8 bytes to the structures */ //printf("\t\tLoad i = %d\n", i); for(j = 0; j < 4; j++) { for (l = 0; l < 4; l++) { r0[j].val[l] = vld1_u8(src + j*total_elements + l*4*total_elements + k*8); //printf("r0[%d].val[%d] = ",j,l); //printmem8(r0[j].val[l]); } } /* Extended table look up to rearrange the distribution of the structures */ for(j = 0; j < 4; j++) { r1[0].val[j] = vtbx4_u8(r1[0].val[j], r0[0], vld1_u8(index1_top +j*8)); r1[0].val[j] = vtbx4_u8(r1[0].val[j], r0[1], vld1_u8(index1_top + 32 + j*8)); r1[1].val[j] = vtbx4_u8(r1[1].val[j], r0[2], vld1_u8(index1_top + j*8)); r1[1].val[j] = vtbx4_u8(r1[1].val[j], r0[3], vld1_u8(index1_top + 32 + j*8)); r1[2].val[j] = vtbx4_u8(r1[2].val[j], r0[0], vld1_u8(index1_bottom + j*8)); r1[2].val[j] = vtbx4_u8(r1[2].val[j], r0[1], vld1_u8(index1_bottom + 32 + j*8)); r1[3].val[j] = vtbx4_u8(r1[3].val[j], r0[2], vld1_u8(index1_bottom + j*8)); r1[3].val[j] = vtbx4_u8(r1[3].val[j], r0[3], vld1_u8(index1_bottom + 32 + j*8)); } for(j = 0; j < 4; j++) { r0[0].val[j] = vtbx4_u8(r0[0].val[j], r1[0], vld1_u8(index2_top + j*8)); r0[0].val[j] = vtbx4_u8(r0[0].val[j], r1[1], vld1_u8(index2_top + 32 + j*8)); r0[1].val[j] = vtbx4_u8(r0[1].val[j], r1[0], vld1_u8(index2_bottom + j*8)); r0[1].val[j] = vtbx4_u8(r0[1].val[j], r1[1], vld1_u8(index2_bottom + 32 + j*8)); r0[2].val[j] = vtbx4_u8(r0[2].val[j], r1[2], vld1_u8(index2_top + j*8)); r0[2].val[j] = vtbx4_u8(r0[2].val[j], r1[3], vld1_u8(index2_top + 32 + j*8)); r0[3].val[j] = vtbx4_u8(r0[3].val[j], r1[2], vld1_u8(index2_bottom + j*8)); r0[3].val[j] = vtbx4_u8(r0[3].val[j], r1[3], vld1_u8(index2_bottom + 32 + j*8)); } /*printf("Objetivo final :\n"); for (j=0;j<4;j++) { for(l=0;l<4;l++) { printf("r0[%d].val[%d] = ",j,l); printmem8(r0[j].val[l]); } }*/ for(j = 0; j < 4; j++) { for(l = 0; l < 4; l++) { vst1_u8(dest + l*8 + j*32 + i, r0[j].val[l]); } } } } void main() { uint8_t *src = "\xcb\x45\x56\x73\xbc\x44\x53\x88\xcb\x45\x56\x73\xbc\x44\x53\x88\x0\x0" "\xff\x3e\x93\x4c\x2d\x3a\xa7\x4f\xff\x3e\x93\x4c\x2d\x3a\xa7\x4f\x0\x0" "\xf1\x5f\xab\xd3\x3f\x11\xc6\xdd\xf1\x5f\xab\xd3\x3f\x11\xc6\xdd\x0\x0" "\x79\xdf\xc3\x12\x7c\x4f\xb3\x66\x79\xdf\xc3\x12\x7c\x4f\xb3\x66\x0\x0" "\x24\xa2\x61\x3f\xf8\xf2\x71\xbf\x24\xa2\x61\x3f\xf8\xf2\x71\xbf\x0\x0" "\x7c\x43\xa8\xcf\xb4\x41\xc8\xc5\x7c\x43\xa8\xcf\xb4\x41\xc8\xc5\x0\x0" "\xb1\x41\x7d\x46\xb9\x31\x83\xd6\xb1\x41\x7d\x46\xb9\x31\x83\xd6\x0\x0" "\x58\x25\xfc\x94\xa8\xb8\x27\x42\x58\x25\xfc\x94\xa8\xb8\x27\x42\x0\x0" "\x69\x77\xbb\xba\xc9\x19\xb3\x33\x69\x77\xbb\xba\xc9\x19\xb3\x33\x0\x0" "\xd2\xae\x98\xfa\x9f\xbe\x45\x18\xd2\xae\x98\xfa\x9f\xbe\x45\x18\x0\x0" "\xee\xfd\xf6\x49\x8d\xad\x82\x33\xee\xfd\xf6\x49\x8d\xad\x82\x33\x0\x0" "\xdd\x22\xd1\x83\x9d\x72\xd8\xf7\xdd\x22\xd1\x83\x9d\x72\xd8\xf7\x0\x0" "\x99\x19\x29\x71\x11\xdc\x95\xaf\x99\x19\x29\x71\x11\xdc\x95\xaf\x0\x0" "\x9a\x1a\xce\x1e\xc4\x3a\x9e\xab\x9a\x1a\xce\x1e\xc4\x3a\x9e\xab\x0\x0" "\x7a\x38\xe7\x35\xc3\xbc\x71\x42\x7a\x38\xe7\x35\xc3\xbc\x71\x42\x0\x0" "\x86\x2b\x58\x5f\x23\x34\x92\x47\x86\x2b\x58\x5f\x23\x34\x92\x47\x0\x0"; uint8_t *dest = calloc(288,2); size_t vectorizable_elements = 16; size_t total_elements = 18; unshuffle16_neon(dest, src, vectorizable_elements, total_elements); printf("vst1q_u8 \n"); printmem(dest); printmem(dest+32); printmem(dest+64); printmem(dest+96); printmem(dest+128); printmem(dest+160); printmem(dest+192); printmem(dest+224); printmem(dest+256); free(dest); }
clayne/c-blosc2
bench/zero_runlen.c
/* Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) Benchmark showing Blosc zero detection capabilities via run-length. */ #include <stdio.h> #include <stdint.h> #include <assert.h> #include <math.h> #include <inttypes.h> #include "blosc2.h" #define KB 1024 #define MB (1024*KB) #define GB (1024*MB) #define NCHUNKS (2000) #define CHUNKSIZE (500 * 1000) // > NCHUNKS for the bench purposes #define NTHREADS 8 enum { ZERO_DETECTION = 0, CHECK_ZEROS = 1, CHECK_NANS = 2, CHECK_VALUES = 3, CHECK_UNINIT = 4, }; #define REPEATED_VALUE 1 int check_special_values(int svalue) { blosc2_schunk *schunk; int32_t isize = CHUNKSIZE * sizeof(int32_t); int32_t osize = CHUNKSIZE * sizeof(int32_t) + BLOSC_MAX_OVERHEAD; int dsize, csize; int64_t nbytes, frame_len; int nchunk; int64_t nchunks = 0; int rc; int32_t value = REPEATED_VALUE; float fvalue; blosc_timestamp_t last, current; double totaltime; double totalsize = (double)isize * NCHUNKS; int32_t *data_buffer = malloc(CHUNKSIZE * sizeof(int32_t)); int32_t *rec_buffer = malloc(CHUNKSIZE * sizeof(int32_t)); /* Initialize the Blosc compressor */ blosc_init(); /* Create a super-chunk container */ blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.typesize = sizeof(int32_t); cparams.compcode = BLOSC_BLOSCLZ; cparams.clevel = 9; cparams.nthreads = NTHREADS; blosc2_storage storage = {.cparams=&cparams, .contiguous=false}; schunk = blosc2_schunk_new(&storage); void* chunk = malloc(BLOSC_EXTENDED_HEADER_LENGTH + isize); // Cache the special chunks switch (svalue) { case ZERO_DETECTION: memset(data_buffer, 0, isize); csize = blosc2_compress(5, 1, sizeof(int32_t), data_buffer, isize, chunk, osize); break; case CHECK_ZEROS: csize = blosc2_chunk_zeros(cparams, isize, chunk, BLOSC_EXTENDED_HEADER_LENGTH); break; case CHECK_UNINIT: csize = blosc2_chunk_uninit(cparams, isize, chunk, BLOSC_EXTENDED_HEADER_LENGTH); break; case CHECK_NANS: csize = blosc2_chunk_nans(cparams, isize, chunk, BLOSC_EXTENDED_HEADER_LENGTH); break; case CHECK_VALUES: csize = blosc2_chunk_repeatval(cparams, isize, chunk, BLOSC_EXTENDED_HEADER_LENGTH + sizeof(int32_t), &value); break; default: printf("Unknown case\n"); exit(1); } if (csize < 0) { printf("Error creating chunk: %d\n", csize); exit(1); } /* Append the chunks */ blosc_set_timestamp(&last); for (nchunk = 0; nchunk < NCHUNKS; nchunk++) { nchunks = blosc2_schunk_append_chunk(schunk, chunk, true); if (nchunks < 0) { printf("Error appending chunk: %" PRId64 "\n", nchunks); exit(1); } } blosc_set_timestamp(&current); free(chunk); totaltime = blosc_elapsed_secs(last, current); printf("\n[Compr] Elapsed time:\t %6.3f s." " Processed data: %.3f GB (%.3f GB/s)\n", totaltime, totalsize / GB, totalsize / (GB * totaltime)); /* Gather some info */ nbytes = schunk->nbytes; frame_len = blosc2_schunk_frame_len(schunk); printf("Compression super-chunk: %ld -> %ld (%.1fx)\n", (long)nbytes, (long)frame_len, (1. * (double)nbytes) / (double)frame_len); /* Retrieve and decompress the chunks */ blosc_set_timestamp(&last); for (nchunk = 0; nchunk < NCHUNKS; nchunk++) { dsize = blosc2_schunk_decompress_chunk(schunk, nchunk, rec_buffer, isize); if (dsize < 0) { printf("Decompression error. Error code: %d\n", dsize); exit(dsize); } assert (dsize == (int)isize); } blosc_set_timestamp(&current); totaltime = blosc_elapsed_secs(last, current); totalsize = (double)(isize) * (double)nchunks; printf("[Decompr] Elapsed time:\t %6.3f s." " Processed data: %.3f GB (%.3f GB/s)\n", totaltime, totalsize / GB, totalsize / (GB * totaltime)); /* Exercise the getitem */ blosc_set_timestamp(&last); for (nchunk = 0; nchunk < NCHUNKS; nchunk++) { bool needs_free; uint8_t* chunk_; csize = blosc2_schunk_get_chunk(schunk, nchunk, &chunk_, &needs_free); if (csize < 0) { printf("blosc2_schunk_get_chunk error. Error code: %d\n", dsize); return csize; } switch (svalue) { case CHECK_VALUES: rc = blosc_getitem(chunk_, nchunk, 1, &value); if (rc < 0) { printf("Error in getitem of a special value\n"); return rc; } if (value != REPEATED_VALUE) { printf("Wrong value!"); exit(1); } break; case CHECK_NANS: rc = blosc_getitem(chunk_, nchunk, 1, &fvalue); if (rc < 0) { printf("Error in getitem of a special value\n"); return rc; } if (!isnan(fvalue)) { printf("Wrong value!"); exit(1); } break; case CHECK_ZEROS: rc = blosc_getitem(chunk_, nchunk, 1, &value); if (rc < 0) { printf("Error in getitem of zeros value\n"); return rc; } if (value != 0) { printf("Wrong value!"); exit(1); } break; default: // It can only be non-initialized rc = blosc_getitem(chunk_, nchunk, 1, &value); if (rc < 0) { printf("Error in getitem of an non-initialized value\n"); return rc; } } if (needs_free) { free(chunk_); } } blosc_set_timestamp(&current); totaltime = blosc_elapsed_secs(last, current); printf("[getitem] Elapsed time:\t %6.3f s.\n", totaltime); // /* Check that all the values have a good roundtrip */ // blosc_set_timestamp(&last); // for (nchunk = 0; nchunk < NCHUNKS; nchunk++) { // dsize = blosc2_schunk_decompress_chunk(schunk, nchunk, (void *) rec_buffer, isize); // if (dsize < 0) { // printf("Decompression error. Error code: %d\n", dsize); // return dsize; // } // assert (dsize == (int)isize); // if (CHECK_VALUE) { // int32_t* buffer = (int32_t*)rec_buffer; // for (int i = 0; i < CHUNKSIZE; i++) { // if (buffer[i] != REPEATED_VALUE) { // printf("Value is not correct in chunk %d, position: %d\n", nchunk, i); // return -1; // } // } // } // else if (CHECK_NAN) { // float* buffer = (float*)rec_buffer; // for (int i = 0; i < CHUNKSIZE; i++) { // if (!isnan(buffer[i])) { // printf("Value is not correct in chunk %d, position: %d\n", nchunk, i); // return -1; // } // } // } // else { // int32_t* buffer = (int32_t*)rec_buffer; // for (int i = 0; i < CHUNKSIZE; i++) { // if (buffer[i] != 0) { // printf("Value is not correct in chunk %d, position: %d\n", nchunk, i); // return -1; // } // } // } // } // printf("All data did a good roundtrip!\n"); /* Free resources */ free(data_buffer); free(rec_buffer); /* Destroy the super-chunk */ blosc2_schunk_free(schunk); /* Destroy the Blosc environment */ blosc_destroy(); return 0; } int main(void) { int rc; printf("*** Testing special zeros..."); rc = check_special_values(CHECK_ZEROS); if (rc < 0) { return rc; } printf("*** Testing NaNs..."); rc = check_special_values(CHECK_NANS); if (rc < 0) { return rc; } printf("*** Testing repeated values..."); rc = check_special_values(CHECK_VALUES); if (rc < 0) { return rc; } printf("*** Testing non-initialized values..."); rc = check_special_values(CHECK_UNINIT); if (rc < 0) { return rc; } printf("Testing zero detection..."); rc = check_special_values(ZERO_DETECTION); if (rc < 0) { return rc; } }
clayne/c-blosc2
examples/urfilters.c
/* Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) Example program demonstrating use of the Blosc filter from C code. To compile this program: $ gcc urfilters.c -o urfilters -lblosc2 To run: $ ./urfilters */ #include "stdio.h" #include <blosc2.h> #define KB 1024. #define MB (1024*KB) #define GB (1024*MB) #define CHUNKSIZE (1000 * 1000) #define NCHUNKS 100 #define NTHREADS 4 int filter_forward(const uint8_t* src, uint8_t* dest, int32_t size, uint8_t meta, blosc2_cparams *cparams) { BLOSC_UNUSED_PARAM(meta); blosc2_schunk *schunk = cparams->schunk; for (int i = 0; i < size / schunk->typesize; ++i) { switch (schunk->typesize) { case 8: ((int64_t *) dest)[i] = ((int64_t *) src)[i] + 1; break; case 4: ((int32_t *) dest)[i] = ((int32_t *) src)[i] + 1; break; case 2: ((int16_t *) dest)[i] = (int16_t)(((int16_t *) src)[i] + 1); break; default: BLOSC_TRACE_ERROR("Item size %d not supported", schunk->typesize); return BLOSC2_ERROR_FAILURE; } } return BLOSC2_ERROR_SUCCESS; } int filter_backward(const uint8_t* src, uint8_t* dest, int32_t size, uint8_t meta, blosc2_dparams *dparams) { BLOSC_UNUSED_PARAM(meta); blosc2_schunk *schunk = dparams->schunk; for (int i = 0; i < size / schunk->typesize; ++i) { switch (schunk->typesize) { case 8: ((int64_t *) dest)[i] = ((int64_t *) src)[i] - 1; break; case 4: ((int32_t *) dest)[i] = ((int32_t *) src)[i] - 1; break; case 2: ((int16_t *) dest)[i] = (int16_t)(((int16_t *) src)[i] - 1); break; default: BLOSC_TRACE_ERROR("Item size %d not supported", schunk->typesize); return BLOSC2_ERROR_FAILURE; } } return BLOSC2_ERROR_SUCCESS; } int main(void) { static int32_t data[CHUNKSIZE]; static int32_t data_dest[CHUNKSIZE]; int32_t isize = CHUNKSIZE * sizeof(int32_t); int dsize; int64_t nbytes, cbytes; blosc2_filter urfilter; urfilter.id = 250; urfilter.forward = filter_forward; urfilter.backward = filter_backward; blosc2_register_filter(&urfilter); blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.filters[4] = urfilter.id; cparams.filters_meta[4] = 0; blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS; blosc2_schunk* schunk; int i, nchunk; blosc_timestamp_t last, current; double ttotal; printf("Blosc version info: %s (%s)\n", blosc_get_version_string(), BLOSC_VERSION_DATE); /* Create a super-chunk container */ cparams.typesize = sizeof(int32_t); cparams.clevel = 9; blosc2_storage storage = {.cparams=&cparams, .dparams=&dparams}; schunk = blosc2_schunk_new(&storage); blosc_set_timestamp(&last); for (nchunk = 0; nchunk < NCHUNKS; nchunk++) { for (i = 0; i < CHUNKSIZE; i++) { data[i] = i * nchunk; } int64_t nchunks = blosc2_schunk_append_buffer(schunk, data, isize); if (nchunks != nchunk + 1) { printf("Unexpected nchunks!"); return -1; } } /* Gather some info */ nbytes = schunk->nbytes; cbytes = schunk->cbytes; blosc_set_timestamp(&current); ttotal = blosc_elapsed_secs(last, current); printf("Compression ratio: %.1f MB -> %.1f MB (%.1fx)\n", (double)nbytes / MB, (double)cbytes / MB, (1. * (double)nbytes) / (double)cbytes); printf("Compression time: %.3g s, %.1f MB/s\n", ttotal, (double)nbytes / (ttotal * MB)); /* Retrieve and decompress the chunks (0-based count) */ blosc_set_timestamp(&last); for (nchunk = NCHUNKS-1; nchunk >= 0; nchunk--) { dsize = blosc2_schunk_decompress_chunk(schunk, nchunk, data_dest, isize); if (dsize < 0) { printf("Decompression error. Error code: %d\n", dsize); return dsize; } } blosc_set_timestamp(&current); ttotal = blosc_elapsed_secs(last, current); printf("Decompression time: %.3g s, %.1f MB/s\n", ttotal, (double)nbytes / (ttotal * MB)); /* Check integrity of the second chunk (made of non-zeros) */ blosc2_schunk_decompress_chunk(schunk, 1, data_dest, isize); for (i = 0; i < CHUNKSIZE; i++) { if (data_dest[i] != i) { printf("Decompressed data differs from original %d, %d!\n", i, data_dest[i]); return -1; } } printf("Successful roundtrip data <-> schunk !\n"); /* Free resources */ /* Destroy the super-chunk */ blosc2_schunk_free(schunk); return 0; }
clayne/c-blosc2
tests/test_bitshuffle_leftovers.c
/********************************************************************* Blosc - Blocked Shuffling and Compression Library Unit test for the bitshuffle with blocks that are not aligned. See https://github.com/Blosc/python-blosc/issues/220 Probably related: https://github.com/Blosc/c-blosc/issues/240 Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSES/BLOSC.txt for details about copyright and rights to use. **********************************************************************/ #include "test_common.h" /* Global vars */ int tests_run = 0; int size; int32_t *data; int32_t *data_out; int32_t *data_dest; static char* test_roundtrip_bitshuffle8(void) { /* Compress with bitshuffle active */ int isize = size; int osize = size + BLOSC_MIN_HEADER_LENGTH; int csize = blosc_compress(9, BLOSC_BITSHUFFLE, 8, isize, data, data_out, osize); mu_assert("ERROR: Compression error", csize > 0); printf("Compression: %d -> %d (%.1fx)\n", isize, csize, (1.*isize) / csize); FILE *fout = fopen("test-bitshuffle8-nomemcpy.cdata", "wb"); fwrite(data_out, csize, 1, fout); fclose(fout); /* Decompress */ int dsize = blosc_decompress(data_out, data_dest, isize); mu_assert("ERROR: Decompression error.", dsize > 0); printf("Decompression successful!\n"); int exit_code = memcmp(data, data_dest, size) ? EXIT_FAILURE : EXIT_SUCCESS; mu_assert("Decompressed data differs from original!", exit_code == EXIT_SUCCESS); return EXIT_SUCCESS; } static char* test_roundtrip_bitshuffle4(void) { /* Compress with bitshuffle active */ int isize = size; int osize = size + BLOSC_MIN_HEADER_LENGTH; int csize = blosc_compress(9, BLOSC_BITSHUFFLE, 4, isize, data, data_out, osize); mu_assert("ERROR: Buffer is uncompressible. Giving up.", csize != 0); mu_assert("ERROR: Compression error.", csize > 0); printf("Compression: %d -> %d (%.1fx)\n", isize, csize, (1.*isize) / csize); FILE *fout = fopen("test-bitshuffle4-memcpy.cdata", "wb"); fwrite(data_out, csize, 1, fout); fclose(fout); /* Decompress */ int dsize = blosc_decompress(data_out, data_dest, isize); mu_assert("ERROR: Decompression error.", dsize >= 0); printf("Decompression successful!\n"); int exit_code = memcmp(data, data_dest, size) ? EXIT_FAILURE : EXIT_SUCCESS; mu_assert("ERROR: Decompressed data differs from original!", exit_code == EXIT_SUCCESS); return EXIT_SUCCESS; } static char *all_tests(void) { /* `size` below is chosen so that it is not divisible by 8 * (not supported by bitshuffle) and in addition, it is not * divisible by 8 (typesize) again. */ size = 641092; data = malloc(size); data_out = malloc(size + BLOSC_MIN_HEADER_LENGTH); data_dest = malloc(size); /* Initialize data */ for (int i = 0; i < (int) (size / sizeof(int32_t)); i++) { ((uint32_t*)data)[i] = i; } /* leftovers */ for (int i = size / (int)sizeof(int32_t) * (int)sizeof(int32_t); i < size; i++) { ((uint8_t*)data)[i] = (uint8_t) i; } mu_run_test(test_roundtrip_bitshuffle4); mu_run_test(test_roundtrip_bitshuffle8); free(data); free(data_out); free(data_dest); return EXIT_SUCCESS; } int main(void) { char* result; blosc_init(); blosc_set_nthreads(1); blosc_set_compressor("lz4"); printf("Blosc version info: %s (%s)\n", BLOSC_VERSION_STRING, BLOSC_VERSION_DATE); /* Run all the suite */ result = all_tests(); if (result != EXIT_SUCCESS) { printf(" (%s)\n", result); } else { printf(" ALL TESTS PASSED"); } printf("\tTests run: %d\n", tests_run); blosc_destroy(); return result != EXIT_SUCCESS; }
clayne/c-blosc2
contrib/bitshuffle_neon/bitshuffle8_neon/bitshuffle8_neon_bucle.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <arm_neon.h> #include <string.h> #define CHECK_MULT_EIGHT(n) if (n % 8) exit(0); static void printmem8_l(uint8x8_t buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]); } static void printmem8x16(uint8x16_t buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], buf[14], buf[15]); } static void printmem16(uint8_t* buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], buf[14], buf[15]); } int32_t _mm_movemask_epi8_neon(uint8x16_t input) { const int8_t __attribute__ ((aligned (16))) xr[8] = {-7,-6,-5,-4,-3,-2,-1,0}; uint8x8_t mask_and = vdup_n_u8(0x80); int8x8_t mask_shift = vld1_s8(xr); uint8x8_t lo = vget_low_u8(input); uint8x8_t hi = vget_high_u8(input); lo = vand_u8(lo, mask_and); lo = vshl_u8(lo, mask_shift); hi = vand_u8(hi, mask_and); hi = vshl_u8(hi, mask_shift); lo = vpadd_u8(lo,lo); lo = vpadd_u8(lo,lo); lo = vpadd_u8(lo,lo); hi = vpadd_u8(hi,hi); hi = vpadd_u8(hi,hi); hi = vpadd_u8(hi,hi); return ((hi[0] << 8) | (lo[0] & 0xFF)); } static void bitshuffle8_neon(const uint8_t* const src, uint8_t* dest, const size_t nbyte) { const size_t elem_size = 8; size_t i, j, k; uint8x8x2_t r0[4]; uint16x4x2_t r1[4]; uint32x2x2_t r2[4]; const int8_t __attribute__ ((aligned (16))) xr[8] = {0,1,2,3,4,5,6,7}; uint8x8_t mask_and = vdup_n_u8(0x01); int8x8_t mask_shift = vld1_s8(xr); CHECK_MULT_EIGHT(nbyte); for (i = 0, k = 0; i < nbyte; i += 64, k++) { /* Load and interleave groups of 8 bytes (64 bytes) to the structure r0 */ r0[0] = vzip_u8(vld1_u8(src + i + 0*8), vld1_u8(src + i +1*8)); r0[1] = vzip_u8(vld1_u8(src + i + 2*8), vld1_u8(src + i +3*8)); r0[2] = vzip_u8(vld1_u8(src + i + 4*8), vld1_u8(src + i +5*8)); r0[3] = vzip_u8(vld1_u8(src + i + 6*8), vld1_u8(src + i +7*8)); /* Interleave 16 bytes */ r1[0] = vzip_u16(vreinterpret_u16_u8(r0[0].val[0]), vreinterpret_u16_u8(r0[1].val[0])); r1[1] = vzip_u16(vreinterpret_u16_u8(r0[0].val[1]), vreinterpret_u16_u8(r0[1].val[1])); r1[2] = vzip_u16(vreinterpret_u16_u8(r0[2].val[0]), vreinterpret_u16_u8(r0[3].val[0])); r1[3] = vzip_u16(vreinterpret_u16_u8(r0[2].val[1]), vreinterpret_u16_u8(r0[3].val[1])); /* Interleave 32 bytes */ r2[0] = vzip_u32(vreinterpret_u32_u16(r1[0].val[0]), vreinterpret_u32_u16(r1[2].val[0])); r2[1] = vzip_u32(vreinterpret_u32_u16(r1[0].val[1]), vreinterpret_u32_u16(r1[2].val[1])); r2[2] = vzip_u32(vreinterpret_u32_u16(r1[1].val[0]), vreinterpret_u32_u16(r1[3].val[0])); r2[3] = vzip_u32(vreinterpret_u32_u16(r1[1].val[1]), vreinterpret_u32_u16(r1[3].val[1])); printf("\n"); printmem8_l(vreinterpret_u8_u32(r2[0].val[0])); printmem8_l(vreinterpret_u8_u32(r2[0].val[1])); printmem8_l(vreinterpret_u8_u32(r2[1].val[0])); printmem8_l(vreinterpret_u8_u32(r2[1].val[1])); printmem8_l(vreinterpret_u8_u32(r2[2].val[0])); printmem8_l(vreinterpret_u8_u32(r2[2].val[1])); printmem8_l(vreinterpret_u8_u32(r2[3].val[0])); printmem8_l(vreinterpret_u8_u32(r2[3].val[1])); printf("\n"); for (j = 0; j < 8; j++) { r0[0].val[0] = vand_u8(vreinterpret_u8_u32(r2[0].val[0]), mask_and); r0[0].val[0] = vshl_u8(r0[0].val[0], mask_shift); r0[0].val[1] = vand_u8(vreinterpret_u8_u32(r2[0].val[1]), mask_and); r0[0].val[1] = vshl_u8(r0[0].val[1], mask_shift); r0[1].val[0] = vand_u8(vreinterpret_u8_u32(r2[1].val[0]), mask_and); r0[1].val[0] = vshl_u8(r0[1].val[0], mask_shift); r0[1].val[1] = vand_u8(vreinterpret_u8_u32(r2[1].val[1]), mask_and); r0[1].val[1] = vshl_u8(r0[1].val[1], mask_shift); r0[2].val[0] = vand_u8(vreinterpret_u8_u32(r2[2].val[0]), mask_and); r0[2].val[0] = vshl_u8(r0[2].val[0], mask_shift); r0[2].val[1] = vand_u8(vreinterpret_u8_u32(r2[2].val[1]), mask_and); r0[2].val[1] = vshl_u8(r0[2].val[1], mask_shift); r0[3].val[0] = vand_u8(vreinterpret_u8_u32(r2[3].val[0]), mask_and); r0[3].val[0] = vshl_u8(r0[3].val[0], mask_shift); r0[3].val[1] = vand_u8(vreinterpret_u8_u32(r2[3].val[1]), mask_and); r0[3].val[1] = vshl_u8(r0[3].val[1], mask_shift); r0[0].val[0] = vpadd_u8(r0[0].val[0], r0[0].val[0]); r0[0].val[0] = vpadd_u8(r0[0].val[0], r0[0].val[0]); r0[0].val[0] = vpadd_u8(r0[0].val[0], r0[0].val[0]); r0[0].val[1] = vpadd_u8(r0[0].val[1], r0[0].val[1]); r0[0].val[1] = vpadd_u8(r0[0].val[1], r0[0].val[1]); r0[0].val[1] = vpadd_u8(r0[0].val[1], r0[0].val[1]); r0[1].val[0] = vpadd_u8(r0[1].val[0], r0[1].val[0]); r0[1].val[0] = vpadd_u8(r0[1].val[0], r0[1].val[0]); r0[1].val[0] = vpadd_u8(r0[1].val[0], r0[1].val[0]); r0[1].val[1] = vpadd_u8(r0[1].val[1], r0[1].val[1]); r0[1].val[1] = vpadd_u8(r0[1].val[1], r0[1].val[1]); r0[1].val[1] = vpadd_u8(r0[1].val[1], r0[1].val[1]); r0[2].val[0] = vpadd_u8(r0[2].val[0], r0[2].val[0]); r0[2].val[0] = vpadd_u8(r0[2].val[0], r0[2].val[0]); r0[2].val[0] = vpadd_u8(r0[2].val[0], r0[2].val[0]); r0[2].val[1] = vpadd_u8(r0[2].val[1], r0[2].val[1]); r0[2].val[1] = vpadd_u8(r0[2].val[1], r0[2].val[1]); r0[2].val[1] = vpadd_u8(r0[2].val[1], r0[2].val[1]); r0[3].val[0] = vpadd_u8(r0[3].val[0], r0[3].val[0]); r0[3].val[0] = vpadd_u8(r0[3].val[0], r0[3].val[0]); r0[3].val[0] = vpadd_u8(r0[3].val[0], r0[3].val[0]); r0[3].val[1] = vpadd_u8(r0[3].val[1], r0[3].val[1]); r0[3].val[1] = vpadd_u8(r0[3].val[1], r0[3].val[1]); r0[3].val[1] = vpadd_u8(r0[3].val[1], r0[3].val[1]); /* int s, t; for(s = 0; s < 4; s++) { for(t = 0; t < 2; t++) { printf("r[%d].val[%d] = ", s, t); printmem8_l(r0[s].val[t]); } } printf("\n");*/ r2[0].val[0] = vreinterpret_u8_u32(vshr_n_u8(vreinterpret_u8_u32(r2[0].val[0]), 1)); r2[0].val[1] = vreinterpret_u8_u32(vshr_n_u8(vreinterpret_u8_u32(r2[0].val[1]), 1)); r2[1].val[0] = vreinterpret_u8_u32(vshr_n_u8(vreinterpret_u8_u32(r2[1].val[0]), 1)); r2[1].val[1] = vreinterpret_u8_u32(vshr_n_u8(vreinterpret_u8_u32(r2[1].val[1]), 1)); r2[2].val[0] = vreinterpret_u8_u32(vshr_n_u8(vreinterpret_u8_u32(r2[2].val[0]), 1)); r2[2].val[1] = vreinterpret_u8_u32(vshr_n_u8(vreinterpret_u8_u32(r2[2].val[1]), 1)); r2[3].val[0] = vreinterpret_u8_u32(vshr_n_u8(vreinterpret_u8_u32(r2[3].val[0]), 1)); r2[3].val[1] = vreinterpret_u8_u32(vshr_n_u8(vreinterpret_u8_u32(r2[3].val[1]), 1)); vst1_lane_u8(dest + k + j*nbyte/(8*elem_size), r0[0].val[0], 0); vst1_lane_u8(dest + k + j*nbyte/(8*elem_size) + nbyte/8, r0[0].val[1], 0); vst1_lane_u8(dest + k + j*nbyte/(8*elem_size) + nbyte/4, r0[1].val[0], 0); vst1_lane_u8(dest + k + j*nbyte/(8*elem_size) + 3*nbyte/8, r0[1].val[1], 0); vst1_lane_u8(dest + k + j*nbyte/(8*elem_size) + nbyte/2, r0[2].val[0], 0); vst1_lane_u8(dest + k + j*nbyte/(8*elem_size) + 5*nbyte/8, r0[2].val[1], 0); vst1_lane_u8(dest + k + j*nbyte/(8*elem_size) + 3*nbyte/4, r0[3].val[0], 0); vst1_lane_u8(dest + k + j*nbyte/(8*elem_size) + 7*nbyte/8, r0[3].val[1], 0); } } } void main() { const uint8_t *src = "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47"; uint8_t *dest = calloc(512,1); size_t size = 512; bitshuffle8_neon(src, dest, size); printmem16(dest); printmem16(dest + 16); printmem16(dest + 32); printmem16(dest + 48); printmem16(dest + 64); printmem16(dest + 80); printmem16(dest + 96); printmem16(dest + 112); printmem16(dest + 128); printmem16(dest + 144); printmem16(dest + 160); printmem16(dest + 176); printmem16(dest + 192); printmem16(dest + 208); printmem16(dest + 224); printmem16(dest + 240); printmem16(dest + 256); printmem16(dest + 272); printmem16(dest + 288); printmem16(dest + 304); printmem16(dest + 320); printmem16(dest + 336); printmem16(dest + 352); printmem16(dest + 368); printmem16(dest + 384); printmem16(dest + 400); printmem16(dest + 416); printmem16(dest + 432); printmem16(dest + 448); printmem16(dest + 464); printmem16(dest + 480); printmem16(dest + 496); free(dest); }
clayne/c-blosc2
contrib/shuffle_neon/unshuffle8_neon/unshuffle8_neon_vtbx_bucle.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <arm_neon.h> #include <string.h> static void printmem8(uint8x8_t buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x\n", buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem16(uint8x16_t r0) { uint8_t buf[16]; ((uint8x16_t *)buf)[0] = r0; printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem(uint8_t* buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x," "%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[31], buf[30], buf[29], buf[28], buf[27], buf[26], buf[25], buf[24], buf[23], buf[22], buf[21], buf[20], buf[19], buf[18], buf[17], buf[16], buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } void unshuffle8_neon(uint8_t* const dest, const uint8_t* const src, const size_t vectorizable_elements, const size_t total_elements) { size_t i, j, k, l; static const size_t bytesoftype = 8; uint8x8x4_t r0[2], r1[2]; uint8_t *index = "\x00\x04\x08\x0c\x10\x14\x18\x1c" "\x01\x05\x09\x0d\x11\x15\x19\x1d" "\x02\x06\x0a\x0e\x12\x16\x1a\x1e" "\x03\x07\x0b\x0f\x13\x17\x1b\x1f"; uint8_t *index_top = "\x00\x01\x02\x03\x08\x09\x0a\x0b" "\x10\x11\x12\x13\x18\x19\x1a\x1b" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\x00\x01\x02\x03\x08\x09\x0a\x0b" "\x10\x11\x12\x13\x18\x19\x1a\x1b"; uint8_t *index_bottom = "\x04\x05\x06\x07\x0c\x0d\x0e\x0f" "\x14\x15\x16\x17\x1c\x1d\x1e\x1f" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\x04\x05\x06\x07\x0c\x0d\x0e\x0f" "\x14\x15\x16\x17\x1c\x1d\x1e\x1f"; for(i = 0, k = 0; i < vectorizable_elements*bytesoftype; i += 2*sizeof(r0[0]), k++) { /* Load 8 byte groups to the structures */ for(j = 0; j < 4; j++) { for (l = 0; l < 2; l++) { r0[l].val[j] = vld1_u8(src + total_elements*(j+l*4) + k*sizeof(r0[l].val[j])); } } /* Rearragnement of the structures distribution */ printf("\nReordenamos\n"); for(j = 0; j < 4; j++) { r1[0].val[j] = vtbx4_u8(r1[0].val[j], r0[0], vld1_u8(index_top + j*sizeof(r1[0].val[j]))); r1[0].val[j] = vtbx4_u8(r1[0].val[j], r0[1], vld1_u8(index_top + sizeof(r1[0]) +j*sizeof(r1[0].val[j]))); printf("r1[0].val[%d] = ", j); printmem8(r1[0].val[j]); r1[1].val[j] = vtbx4_u8(r1[1].val[j], r0[0], vld1_u8(index_bottom +j*sizeof(r1[1].val[j]))); r1[1].val[j] = vtbx4_u8(r1[1].val[j], r0[1], vld1_u8(index_bottom + sizeof(r1[1]) +j*sizeof(r1[1 ].val[j]))); printf("\t\t\tr1[1].val[%d] = ", j); printmem8(r1[1].val[j]); } /* Table look up to put together bytes */ for (j = 0; j < 4; j++) { for (l = 0; l < 2; l++) { r0[l].val[j] = vtbl4_u8(r1[l], vld1_u8(index + j*sizeof(r0[l].val[j]))); } } /* Store the results in the destination vector */ for(j = 0; j < 4; j++) { for(l = 0; l < 2; l++) { vst1_u8(dest + i + l*sizeof(r0[l]) + j*sizeof(r0[l].val[j]), r0[l].val[j]); } } } } void main() { uint8_t *src = "\xcb\x69\x45\x77\x56\xbb\x73\xba\xbc\xc9\x44\x19\x53\xb3\x88\x33\x0\x0" "\xff\xd2\x3e\xae\x93\x98\x4c\xfa\x2d\x9f\x3a\xbe\xa7\x45\x4f\x18\x0\x0" "\xf1\xee\x5f\xfd\xab\xf6\xd3\x49\x3f\x8d\x11\xad\xc6\x82\xdd\x33\x0\x0" "\x79\xdd\xdf\x22\xc3\xd1\x12\x83\x7c\x9d\x4f\x72\xb3\xd8\x66\xf7\x0\x0" "\x24\x99\xa2\x19\x61\x29\x3f\x71\xf8\x11\xf2\xdc\x71\x95\xbf\xaf\x0\x0" "\x7c\x9a\x43\x1a\xa8\xce\xcf\x1e\xb4\xc4\x41\x3a\xc8\x9e\xc5\xab\x0\x0" "\xb1\x7a\x41\x38\x7d\xe7\x46\x35\xb9\xc3\x31\xbc\x83\x71\xd6\x42\x0\x0" "\x58\x86\x25\x2b\xfc\x58\x94\x5f\xa8\x23\xb8\x34\x27\x92\x42\x47\x0\x0"; uint8_t *dest = calloc(144,2); size_t vectorizable_elements = 16; size_t total_elements = 18; unshuffle8_neon(dest, src, vectorizable_elements, total_elements); printf("vst1q_u8 \n"); printmem(dest); printmem(dest+32); printmem(dest+64); printmem(dest+96); printmem(dest+128); free(dest); }
clayne/c-blosc2
plugins/plugin_utils.c
<reponame>clayne/c-blosc2 /* Copyright (C) 2021 The Blosc Developers http://blosc.org License: BSD 3-Clause (see LICENSE.txt) */ #include <stdio.h> #include "blosc2.h" #define BLOSC_PLUGINS_MAX_DIM 8 void swap_store(void *dest, const void *pa, int size) { uint8_t *pa_ = (uint8_t *) pa; uint8_t *pa2_ = malloc((size_t) size); int i = 1; /* for big/little endian detection */ char *p = (char *) &i; if (p[0] == 1) { /* little endian */ switch (size) { case 8: pa2_[0] = pa_[7]; pa2_[1] = pa_[6]; pa2_[2] = pa_[5]; pa2_[3] = pa_[4]; pa2_[4] = pa_[3]; pa2_[5] = pa_[2]; pa2_[6] = pa_[1]; pa2_[7] = pa_[0]; break; case 4: pa2_[0] = pa_[3]; pa2_[1] = pa_[2]; pa2_[2] = pa_[1]; pa2_[3] = pa_[0]; break; case 2: pa2_[0] = pa_[1]; pa2_[1] = pa_[0]; break; case 1: pa2_[0] = pa_[0]; break; default: fprintf(stderr, "Unhandled nitems: %d\n", size); } } memcpy(dest, pa2_, size); free(pa2_); } int32_t deserialize_meta(uint8_t *smeta, int32_t smeta_len, int8_t *ndim, int64_t *shape, int32_t *chunkshape, int32_t *blockshape) { BLOSC_UNUSED_PARAM(smeta_len); uint8_t *pmeta = smeta; // Check that we have an array with 5 entries (version, ndim, shape, chunkshape, blockshape) pmeta += 1; // version entry int8_t version = (int8_t)pmeta[0]; // positive fixnum (7-bit positive integer) BLOSC_UNUSED_PARAM(version); pmeta += 1; // ndim entry *ndim = (int8_t)pmeta[0]; int8_t ndim_aux = *ndim; // positive fixnum (7-bit positive integer) pmeta += 1; // shape entry // Initialize to ones, as required by Caterva for (int i = 0; i < BLOSC_PLUGINS_MAX_DIM; i++) shape[i] = 1; pmeta += 1; for (int8_t i = 0; i < ndim_aux; i++) { pmeta += 1; swap_store(shape + i, pmeta, sizeof(int64_t)); pmeta += sizeof(int64_t); } // chunkshape entry // Initialize to ones, as required by Caterva for (int i = 0; i < BLOSC_PLUGINS_MAX_DIM; i++) chunkshape[i] = 1; pmeta += 1; for (int8_t i = 0; i < ndim_aux; i++) { pmeta += 1; swap_store(chunkshape + i, pmeta, sizeof(int32_t)); pmeta += sizeof(int32_t); } // blockshape entry // Initialize to ones, as required by Caterva for (int i = 0; i < BLOSC_PLUGINS_MAX_DIM; i++) blockshape[i] = 1; pmeta += 1; for (int8_t i = 0; i < ndim_aux; i++) { pmeta += 1; swap_store(blockshape + i, pmeta, sizeof(int32_t)); pmeta += sizeof(int32_t); } int32_t slen = (int32_t)(pmeta - smeta); return slen; } void index_multidim_to_unidim(const int64_t *index, int8_t ndim, const int64_t *strides, int64_t *i) { *i = 0; for (int j = 0; j < ndim; ++j) { *i += index[j] * strides[j]; } }
clayne/c-blosc2
contrib/shuffle_neon/shuffle8_neon/shuffle8_neon.c
<reponame>clayne/c-blosc2 /* Routine optimized for shuffling a buffer for a type size of 8 bytes. */ void shuffle8_neon(uint8_t* const dest, const uint8_t* const src, const size_t vectorizable_elements, const size_t total_elements) { size_t i, j, k; static const size_t bytesoftype = 8; uint8x8x2_t r0[4]; uint16x4x2_t r1[4]; uint32x2x2_t r2[4]; for(i = 0, k = 0; i < vectorizable_elements*bytesoftype; i += 64, k++) { /* Load and interleave groups of 8 bytes (64 bytes) to the structure r0 */ r0[0] = vzip_u8(vld1_u8(src + i + 0*8), vld1_u8(src + i +1*8)); r0[1] = vzip_u8(vld1_u8(src + i + 2*8), vld1_u8(src + i +3*8)); r0[2] = vzip_u8(vld1_u8(src + i + 4*8), vld1_u8(src + i +5*8)); r0[3] = vzip_u8(vld1_u8(src + i + 6*8), vld1_u8(src + i +7*8)); /* Interleave 16 bytes */ r1[0] = vzip_u16(vreinterpret_u16_u8(r0[0].val[0]), vreinterpret_u16_u8(r0[1].val[0])); r1[1] = vzip_u16(vreinterpret_u16_u8(r0[0].val[1]), vreinterpret_u16_u8(r0[1].val[1])); r1[2] = vzip_u16(vreinterpret_u16_u8(r0[2].val[0]), vreinterpret_u16_u8(r0[3].val[0])); r1[3] = vzip_u16(vreinterpret_u16_u8(r0[2].val[1]), vreinterpret_u16_u8(r0[3].val[1])); /* Interleave 32 bytes */ r2[0] = vzip_u32(vreinterpret_u32_u16(r1[0].val[0]), vreinterpret_u32_u16(r1[2].val[0])); r2[1] = vzip_u32(vreinterpret_u32_u16(r1[0].val[1]), vreinterpret_u32_u16(r1[2].val[1])); r2[2] = vzip_u32(vreinterpret_u32_u16(r1[1].val[0]), vreinterpret_u32_u16(r1[3].val[0])); r2[3] = vzip_u32(vreinterpret_u32_u16(r1[1].val[1]), vreinterpret_u32_u16(r1[3].val[1])); /* Store the results in the destination vector */ vst1_u8(dest + k*8 + 0*total_elements, vreinterpret_u8_u32(r2[0].val[0])); vst1_u8(dest + k*8 + 1*total_elements, vreinterpret_u8_u32(r2[0].val[1])); vst1_u8(dest + k*8 + 2*total_elements, vreinterpret_u8_u32(r2[1].val[0])); vst1_u8(dest + k*8 + 3*total_elements, vreinterpret_u8_u32(r2[1].val[1])); vst1_u8(dest + k*8 + 4*total_elements, vreinterpret_u8_u32(r2[2].val[0])); vst1_u8(dest + k*8 + 5*total_elements, vreinterpret_u8_u32(r2[2].val[1])); vst1_u8(dest + k*8 + 6*total_elements, vreinterpret_u8_u32(r2[3].val[0])); vst1_u8(dest + k*8 + 7*total_elements, vreinterpret_u8_u32(r2[3].val[1])); } }
clayne/c-blosc2
plugins/codecs/zfp/test_zfp_rate_getitem.c
<reponame>clayne/c-blosc2 /********************************************************************* Blosc - Blocked Shuffling and Compression Library Copyright (C) 2021 The Blosc Developers <<EMAIL>> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. Test program demonstrating use of the Blosc codec from C code. To compile this program: $ gcc -O test_zfp_rate_getitem.c -o test_zfp_rate_getitem -lblosc2 **********************************************************************/ #include <stdio.h> #include <inttypes.h> #include <stdlib.h> #include "blosc2.h" #include "blosc2/codecs-registry.h" static int test_zfp_rate_getitem_float(blosc2_schunk* schunk) { if (schunk->typesize != 4) { printf("Error: This test is only for doubles.\n"); return 0; } int64_t nchunks = schunk->nchunks; int32_t chunksize = (int32_t) (schunk->chunksize); float *data_in = malloc(chunksize); int decompressed; int64_t csize; uint8_t *chunk_zfp = malloc(chunksize + BLOSC_MAX_OVERHEAD); uint8_t *chunk_blosc = malloc(chunksize + BLOSC_MAX_OVERHEAD); float *data_dest = malloc(chunksize); /* Create a context for compression */ int8_t zfp_rate = 37; blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.splitmode = BLOSC_NEVER_SPLIT; cparams.typesize = schunk->typesize; cparams.compcode = BLOSC_CODEC_ZFP_FIXED_RATE; cparams.compcode_meta = zfp_rate; cparams.filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_NOFILTER; cparams.clevel = 5; cparams.nthreads = 1; cparams.blocksize = schunk->blocksize; cparams.schunk = schunk; blosc2_context *cctx; cctx = blosc2_create_cctx(cparams); blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS; dparams.nthreads = 1; dparams.schunk = schunk; blosc2_context *dctx; dctx = blosc2_create_dctx(dparams); int32_t zfp_chunk_nbytes, zfp_chunk_cbytes, blosc_chunk_cbytes; uint8_t *lossy_chunk = malloc(chunksize + BLOSC_MAX_OVERHEAD); for (int ci = 0; ci < nchunks; ci++) { decompressed = blosc2_schunk_decompress_chunk(schunk, ci, data_in, chunksize); if (decompressed < 0) { printf("Error decompressing chunk \n"); return -1; } /* Compress using ZFP fixed-rate */ csize = blosc2_compress_ctx(cctx, data_in, chunksize, chunk_zfp, chunksize + BLOSC_MAX_OVERHEAD); if (csize == 0) { printf("Buffer is uncompressible. Giving up.\n"); return 0; } else if (csize < 0) { printf("Compression error. Error code: %" PRId64 "\n", csize); return (int) csize; } blosc2_cbuffer_sizes(chunk_zfp, &zfp_chunk_nbytes, &zfp_chunk_cbytes, NULL); decompressed = blosc2_decompress_ctx(dctx, chunk_zfp, zfp_chunk_cbytes, lossy_chunk, chunksize); if (decompressed < 0) { printf("Error decompressing chunk \n"); return -1; } /* Compress not using ZFP fixed-rate */ csize = blosc2_compress_ctx(schunk->cctx, lossy_chunk, chunksize, chunk_blosc, chunksize + BLOSC_MAX_OVERHEAD); if (csize == 0) { printf("Buffer is uncompressible. Giving up.\n"); return 0; } else if (csize < 0) { printf("Compression error. Error code: %" PRId64 "\n", csize); return (int) csize; } blosc2_cbuffer_sizes(chunk_blosc, NULL, &blosc_chunk_cbytes, NULL); /* Get item */ int index, dsize_zfp, dsize_blosc; float item_zfp, item_blosc; int nelems = schunk->chunksize / schunk->typesize; for (int i = 0; i < 100; ++i) { srand(i); index = rand() % nelems; // Usual getitem dsize_blosc = blosc2_getitem_ctx(schunk->dctx, chunk_blosc, blosc_chunk_cbytes, index, 1, &item_blosc, sizeof(item_blosc)); // Optimized getitem using ZFP cell machinery dsize_zfp = blosc2_getitem_ctx(dctx, chunk_zfp, zfp_chunk_cbytes, index, 1, &item_zfp, sizeof(item_zfp)); if (dsize_blosc != dsize_zfp) { printf("Different amount of items gotten\n"); return -1; } if (item_blosc != item_zfp) { printf("\nIn index %d different items extracted zfp %f blosc %f\n", index, item_zfp, item_blosc); return -1; } } } free(data_in); free(data_dest); free(chunk_zfp); free(chunk_blosc); free(lossy_chunk); blosc2_free_ctx(cctx); blosc2_free_ctx(dctx); printf("Succesful roundtrip!\n"); return (int) (BLOSC2_ERROR_SUCCESS); } static int test_zfp_rate_getitem_double(blosc2_schunk* schunk) { if (schunk->typesize != 8) { printf("Error: This test is only for doubles.\n"); return 0; } int64_t nchunks = schunk->nchunks; int32_t chunksize = (int32_t) (schunk->chunksize); double *data_in = malloc(chunksize); int decompressed; int64_t csize; uint8_t *chunk_zfp = malloc(chunksize + BLOSC_MAX_OVERHEAD); uint8_t *chunk_blosc = malloc(chunksize + BLOSC_MAX_OVERHEAD); double *data_dest = malloc(chunksize); /* Create a context for compression */ int zfp_rate = 37; blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.splitmode = BLOSC_NEVER_SPLIT; cparams.typesize = schunk->typesize; cparams.compcode = BLOSC_CODEC_ZFP_FIXED_RATE; cparams.compcode_meta = zfp_rate; cparams.filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_NOFILTER; cparams.clevel = 5; cparams.nthreads = 1; cparams.blocksize = schunk->blocksize; cparams.schunk = schunk; blosc2_context *cctx; cctx = blosc2_create_cctx(cparams); blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS; dparams.nthreads = 1; dparams.schunk = schunk; blosc2_context *dctx; dctx = blosc2_create_dctx(dparams); int32_t zfp_chunk_nbytes, zfp_chunk_cbytes, blosc_chunk_cbytes; uint8_t *lossy_chunk = malloc(chunksize + BLOSC_MAX_OVERHEAD); for (int ci = 0; ci < nchunks; ci++) { decompressed = blosc2_schunk_decompress_chunk(schunk, ci, data_in, chunksize); if (decompressed < 0) { printf("Error decompressing chunk \n"); return -1; } /* Compress using ZFP fixed-rate */ csize = blosc2_compress_ctx(cctx, data_in, chunksize, chunk_zfp, chunksize + BLOSC_MAX_OVERHEAD); if (csize == 0) { printf("Buffer is uncompressible. Giving up.\n"); return 0; } else if (csize < 0) { printf("Compression error. Error code: %" PRId64 "\n", csize); return (int) csize; } blosc2_cbuffer_sizes(chunk_zfp, &zfp_chunk_nbytes, &zfp_chunk_cbytes, NULL); decompressed = blosc2_decompress_ctx(dctx, chunk_zfp, zfp_chunk_cbytes, lossy_chunk, chunksize); if (decompressed < 0) { printf("Error decompressing chunk \n"); return -1; } /* Compress not using ZFP fixed-rate */ csize = blosc2_compress_ctx(schunk->cctx, lossy_chunk, chunksize, chunk_blosc, chunksize + BLOSC_MAX_OVERHEAD); if (csize == 0) { printf("Buffer is uncompressible. Giving up.\n"); return 0; } else if (csize < 0) { printf("Compression error. Error code: %" PRId64 "\n", csize); return (int) csize; } blosc2_cbuffer_sizes(chunk_blosc, NULL, &blosc_chunk_cbytes, NULL); /* Get item */ int index, dsize_zfp, dsize_blosc; double item_zfp, item_blosc; int nelems = schunk->chunksize / schunk->typesize; for (int i = 0; i < 100; ++i) { srand(i); index = rand() % nelems; // Usual getitem dsize_blosc = blosc2_getitem_ctx(schunk->dctx, chunk_blosc, blosc_chunk_cbytes, index, 1, &item_blosc, sizeof(item_blosc)); // Optimized getitem using ZFP cell machinery dsize_zfp = blosc2_getitem_ctx(dctx, chunk_zfp, zfp_chunk_cbytes, index, 1, &item_zfp, sizeof(item_zfp)); if (dsize_blosc != dsize_zfp) { printf("Different amount of items gotten\n"); return -1; } if (item_blosc != item_zfp) { printf("\nIn index %d different items extracted zfp %f blosc %f\n", index, item_zfp, item_blosc); return -1; } } } free(data_in); free(data_dest); free(chunk_zfp); free(chunk_blosc); free(lossy_chunk); blosc2_free_ctx(cctx); blosc2_free_ctx(dctx); printf("Succesful roundtrip!\n"); return (int) (BLOSC2_ERROR_SUCCESS); } int float_cyclic() { blosc2_schunk *schunk = blosc2_schunk_open("example_float_cyclic.caterva"); /* Run the test. */ int result = test_zfp_rate_getitem_float(schunk); blosc2_schunk_free(schunk); return result; } int double_same_cells() { blosc2_schunk *schunk = blosc2_schunk_open("example_double_same_cells.caterva"); /* Run the test. */ int result = test_zfp_rate_getitem_double(schunk); blosc2_schunk_free(schunk); return result; } int day_month_temp() { blosc2_schunk *schunk = blosc2_schunk_open("example_day_month_temp.caterva"); /* Run the test. */ int result = test_zfp_rate_getitem_float(schunk); blosc2_schunk_free(schunk); return result; } int item_prices() { blosc2_schunk *schunk = blosc2_schunk_open("example_item_prices.caterva"); /* Run the test. */ int result = test_zfp_rate_getitem_float(schunk); blosc2_schunk_free(schunk); return result; } int main(void) { blosc_init(); // this is mandatory for initiallizing the plugin mechanism printf("float_cyclic: "); float_cyclic(); printf("double_same_cells: "); double_same_cells(); printf("day_month_temp: "); day_month_temp(); printf("item_prices: "); item_prices(); blosc_destroy(); return BLOSC2_ERROR_SUCCESS; }
clayne/c-blosc2
contrib/shuffle_neon/unshuffle16_neon/unshuffle16_neon_vtbx.c
/* Routine for unshuffling a buffer for a type size of 16 bytes. Non-optimized version*/ void unshuffle16_neon(uint8_t* const dest, const uint8_t* const src, const size_t vectorizable_elements, const size_t total_elements) { size_t i, j, k, l; static const size_t bytesoftype = 16; uint8x8x4_t r0[4], r1[4]; uint8_t *index1_top = "\x00\x01\x02\x03\x08\x09\x0a\x0b" "\x10\x11\x12\x13\x18\x19\x1a\x1b" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\x00\x01\x02\x03\x08\x09\x0a\x0b" "\x10\x11\x12\x13\x18\x19\x1a\x1b"; uint8_t *index1_bottom = "\x04\x05\x06\x07\x0c\x0d\x0e\x0f" "\x14\x15\x16\x17\x1c\x1d\x1e\x1f" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff" "\x04\x05\x06\x07\x0c\x0d\x0e\x0f" "\x14\x15\x16\x17\x1c\x1d\x1e\x1f"; uint8_t *index2_top = "\x00\x10\xff\xff\x04\x14\xff\xff" "\x08\x18\xff\xff\x0c\x1c\xff\xff" "\x01\x11\xff\xff\x05\x15\xff\xff" "\x09\x19\xff\xff\x0d\x1d\xff\xff" "\xff\xff\x00\x10\xff\xff\x04\x14" "\xff\xff\x08\x18\xff\xff\x0c\x1c" "\xff\xff\x01\x11\xff\xff\x05\x15" "\xff\xff\x09\x19\xff\xff\x0d\x1d"; uint8_t *index2_bottom = "\x02\x12\xff\xff\x06\x16\xff\xff" "\x0a\x1a\xff\xff\x0e\x1e\xff\xff" "\x03\x13\xff\xff\x07\x17\xff\xff" "\x0b\x1b\xff\xff\x0f\x1f\xff\xff" "\xff\xff\x02\x12\xff\xff\x06\x16" "\xff\xff\x0a\x1a\xff\xff\x0e\x1e" "\xff\xff\x03\x13\xff\xff\x07\x17" "\xff\xff\x0b\x1b\xff\xff\x0f\x1f"; for(i = 0, k = 0; i < vectorizable_elements*bytesoftype; i += 128, k++) { /* Load 16 gorups of 8 bytes to the structures */ for(j = 0; j < 4; j++) { for (l = 0; l < 4; l++) { r0[j].val[l] = vld1_u8(src + j*total_elements + l*4*total_elements + k*8); } } /* Extended table look up to rearrange the distribution of the structures */ for(j = 0; j < 4; j++) { r1[0].val[j] = vtbx4_u8(r1[0].val[j], r0[0], vld1_u8(index1_top +j*8)); r1[0].val[j] = vtbx4_u8(r1[0].val[j], r0[1], vld1_u8(index1_top + 32 + j*8)); r1[1].val[j] = vtbx4_u8(r1[1].val[j], r0[2], vld1_u8(index1_top + j*8)); r1[1].val[j] = vtbx4_u8(r1[1].val[j], r0[3], vld1_u8(index1_top + 32 + j*8)); r1[2].val[j] = vtbx4_u8(r1[2].val[j], r0[0], vld1_u8(index1_bottom + j*8)); r1[2].val[j] = vtbx4_u8(r1[2].val[j], r0[1], vld1_u8(index1_bottom + 32 + j*8)); r1[3].val[j] = vtbx4_u8(r1[3].val[j], r0[2], vld1_u8(index1_bottom + j*8)); r1[3].val[j] = vtbx4_u8(r1[3].val[j], r0[3], vld1_u8(index1_bottom + 32 + j*8)); } for(j = 0; j < 4; j++) { r0[0].val[j] = vtbx4_u8(r0[0].val[j], r1[0], vld1_u8(index2_top + j*8)); r0[0].val[j] = vtbx4_u8(r0[0].val[j], r1[1], vld1_u8(index2_top + 32 + j*8)); r0[1].val[j] = vtbx4_u8(r0[1].val[j], r1[0], vld1_u8(index2_bottom + j*8)); r0[1].val[j] = vtbx4_u8(r0[1].val[j], r1[1], vld1_u8(index2_bottom + 32 + j*8)); r0[2].val[j] = vtbx4_u8(r0[2].val[j], r1[2], vld1_u8(index2_top + j*8)); r0[2].val[j] = vtbx4_u8(r0[2].val[j], r1[3], vld1_u8(index2_top + 32 + j*8)); r0[3].val[j] = vtbx4_u8(r0[3].val[j], r1[2], vld1_u8(index2_bottom + j*8)); r0[3].val[j] = vtbx4_u8(r0[3].val[j], r1[3], vld1_u8(index2_bottom + 32 + j*8)); } for(j = 0; j < 4; j++) { for(l = 0; l < 4; l++) { vst1_u8(dest + l*8 + j*32 + i, r0[j].val[l]); } } } }
clayne/c-blosc2
contrib/shuffle_neon/shuffle2_neon/shuffle2_neon_bucle.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <arm_neon.h> #include <string.h> static void printmem16(uint8x16_t r0) { uint8_t buf[16]; ((uint8x16_t *)buf)[0] = r0; printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem(uint8_t* buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x," "%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[31], buf[30], buf[29], buf[28], buf[27], buf[26], buf[25], buf[24], buf[23], buf[22], buf[21], buf[20], buf[19], buf[18], buf[17], buf[16], buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void shuffle2_neon(uint8_t* const dest, const uint8_t* const src, const size_t vectorizable_elements, const size_t total_elements) { size_t i, j, k; static const size_t bytesoftype = 2; uint8x16x2_t r0; for(i = 0, k = 0; i < vectorizable_elements*bytesoftype; i += 32, k++) { /* Load (and permute) 32 bytes to the structure r0 */ r0 = vld2q_u8(src + i); /* Store the results in the destination vector */ vst1q_u8(dest + total_elements*0 + k*16, r0.val[0]); vst1q_u8(dest + total_elements*1 + k*16, r0.val[1]); } } void main() { uint8_t *src = "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\x13\x21\x17\xc8\xc9\x34\x25\x11\x67\x74\x4e\xe8\x67\x74\x4e\xe8"; uint8_t *dest = calloc(144,1); size_t vectorizable_elements = 64 ; size_t total_elements = 72; shuffle2_neon(dest, src, vectorizable_elements, total_elements); free(dest); printmem(dest); printmem(dest+32); printmem(dest+64); printmem(dest+96); printmem(dest+128); }
clayne/c-blosc2
contrib/bitshuffle_neon/Test/bitshuffle_bitunshuffle_test4.c
<filename>contrib/bitshuffle_neon/Test/bitshuffle_bitunshuffle_test4.c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <arm_neon.h> #include <assert.h> #define CHECK_MULT_EIGHT(n) if (n % 8) exit(0); static void printmem8(uint8x8_t buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x\n", buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem16(uint8x16_t r0) { uint8_t buf[16]; ((uint8x16_t *)buf)[0] = r0; printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } static void printmem(uint8_t* buf) { printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x," "%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n", buf[31], buf[30], buf[29], buf[28], buf[27], buf[26], buf[25], buf[24], buf[23], buf[22], buf[21], buf[20], buf[19], buf[18], buf[17], buf[16], buf[15], buf[14], buf[13], buf[12], buf[11], buf[10], buf[9], buf[8], buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } /* Routine optimized for bit-shuffling a buffer for a type size of 4 bytes. */ static void bitshuffle4_neon(const uint8_t* const src, uint8_t* dest, const size_t nbyte) { const size_t elem_size = 4; uint8x16x4_t x0; size_t i, j, k; uint8x8_t lo_x[4], hi_x[4], lo[4], hi[4]; const int8_t __attribute__ ((aligned (16))) xr[8] = {0,1,2,3,4,5,6,7}; uint8x8_t mask_and = vdup_n_u8(0x01); int8x8_t mask_shift = vld1_s8(xr); /* #define CHECK_MULT_EIGHT(n) if (n % 8) exit(0); */ CHECK_MULT_EIGHT(nbyte); for (i = 0, k = 0; i < nbyte; i += 64, k++) { /* Load 64-byte groups */ x0 = vld4q_u8(src + i); /* Split in 8-bytes grops */ lo_x[0] = vget_low_u8(x0.val[0]); hi_x[0] = vget_high_u8(x0.val[0]); lo_x[1] = vget_low_u8(x0.val[1]); hi_x[1] = vget_high_u8(x0.val[1]); lo_x[2] = vget_low_u8(x0.val[2]); hi_x[2] = vget_high_u8(x0.val[2]); lo_x[3] = vget_low_u8(x0.val[3]); hi_x[3] = vget_high_u8(x0.val[3]); for (j = 0; j < 8; j++) { /* Create mask from the most significant bit of each 8-bit element */ lo[0] = vand_u8(lo_x[0], mask_and); lo[0] = vshl_u8(lo[0], mask_shift); lo[1] = vand_u8(lo_x[1], mask_and); lo[1] = vshl_u8(lo[1], mask_shift); lo[2] = vand_u8(lo_x[2], mask_and); lo[2] = vshl_u8(lo[2], mask_shift); lo[3] = vand_u8(lo_x[3], mask_and); lo[3] = vshl_u8(lo[3], mask_shift); hi[0] = vand_u8(hi_x[0], mask_and); hi[0] = vshl_u8(hi[0], mask_shift); hi[1] = vand_u8(hi_x[1], mask_and); hi[1] = vshl_u8(hi[1], mask_shift); hi[2] = vand_u8(hi_x[2], mask_and); hi[2] = vshl_u8(hi[2], mask_shift); hi[3] = vand_u8(hi_x[3], mask_and); hi[3] = vshl_u8(hi[3], mask_shift); lo[0] = vpadd_u8(lo[0], lo[0]); lo[0] = vpadd_u8(lo[0], lo[0]); lo[0] = vpadd_u8(lo[0], lo[0]); lo[1] = vpadd_u8(lo[1], lo[1]); lo[1] = vpadd_u8(lo[1], lo[1]); lo[1] = vpadd_u8(lo[1], lo[1]); lo[2] = vpadd_u8(lo[2], lo[2]); lo[2] = vpadd_u8(lo[2], lo[2]); lo[2] = vpadd_u8(lo[2], lo[2]); lo[3] = vpadd_u8(lo[3], lo[3]); lo[3] = vpadd_u8(lo[3], lo[3]); lo[3] = vpadd_u8(lo[3], lo[3]); hi[0] = vpadd_u8(hi[0], hi[0]); hi[0] = vpadd_u8(hi[0], hi[0]); hi[0] = vpadd_u8(hi[0], hi[0]); hi[1] = vpadd_u8(hi[1], hi[1]); hi[1] = vpadd_u8(hi[1], hi[1]); hi[1] = vpadd_u8(hi[1], hi[1]); hi[2] = vpadd_u8(hi[2], hi[2]); hi[2] = vpadd_u8(hi[2], hi[2]); hi[2] = vpadd_u8(hi[2], hi[2]); hi[3] = vpadd_u8(hi[3], hi[3]); hi[3] = vpadd_u8(hi[3], hi[3]); hi[3] = vpadd_u8(hi[3], hi[3]); /* Shift packed 8-bit */ lo_x[0] = vshr_n_u8(lo_x[0], 1); hi_x[0] = vshr_n_u8(hi_x[0], 1); lo_x[1] = vshr_n_u8(lo_x[1], 1); hi_x[1] = vshr_n_u8(hi_x[1], 1); lo_x[2] = vshr_n_u8(lo_x[2], 1); hi_x[2] = vshr_n_u8(hi_x[2], 1); lo_x[3] = vshr_n_u8(lo_x[3], 1); hi_x[3] = vshr_n_u8(hi_x[3], 1); /* Store the created mask to the destination vector */ vst1_lane_u8(dest + 2*k + j*nbyte/(8*elem_size), lo[0], 0); vst1_lane_u8(dest + 2*k + j*nbyte/(8*elem_size) + nbyte/4, lo[1], 0); vst1_lane_u8(dest + 2*k + j*nbyte/(8*elem_size) + nbyte/2, lo[2], 0); vst1_lane_u8(dest + 2*k + j*nbyte/(8*elem_size) + 3*nbyte/4, lo[3], 0); vst1_lane_u8(dest + 2*k+1 + j*nbyte/(8*elem_size), hi[0], 0); vst1_lane_u8(dest + 2*k+1 + j*nbyte/(8*elem_size) + nbyte/4, hi[1], 0); vst1_lane_u8(dest + 2*k+1 + j*nbyte/(8*elem_size) + nbyte/2, hi[2], 0); vst1_lane_u8(dest + 2*k+1 + j*nbyte/(8*elem_size) + 3*nbyte/4, hi[3], 0); } } } /* Routine optimized for bit-unshuffling a buffer for a type size of 4 byte. */ static void bitunshuffle4_neon(const uint8_t* const src, uint8_t* dest, const size_t nbyte) { const size_t elem_size = 4; size_t i, j, k; uint8x8_t lo_x[4], hi_x[4], lo[4], hi[4]; const int8_t __attribute__ ((aligned (16))) xr[8] = {0,1,2,3,4,5,6,7}; uint8x8_t mask_and = vdup_n_u8(0x01); int8x8_t mask_shift = vld1_s8(xr); /* #define CHECK_MULT_EIGHT(n) if (n % 8) exit(0); */ CHECK_MULT_EIGHT(nbyte); for (i = 0, k = 0; i < nbyte; i += 64, k++) { for (j = 0; j < 8; j++) { /* Load lanes */ lo_x[0][j] = src[2*k + j*nbyte/(8*elem_size)]; hi_x[0][j] = src[2*k+1 + j*nbyte/(8*elem_size)]; lo_x[1][j] = src[2*k + j*nbyte/(8*elem_size) + nbyte/4]; hi_x[1][j] = src[2*k+1 + j*nbyte/(8*elem_size) + nbyte/4]; lo_x[2][j] = src[2*k + j*nbyte/(8*elem_size) + nbyte/2]; hi_x[2][j] = src[2*k+1 + j*nbyte/(8*elem_size) + nbyte/2]; lo_x[3][j] = src[2*k + j*nbyte/(8*elem_size) + 3*nbyte/4]; hi_x[3][j] = src[2*k+1 + j*nbyte/(8*elem_size) + 3*nbyte/4]; } for (j = 0; j < 8; j++) { /* Create mask from the most significant bit of each 8-bit element */ lo[0] = vand_u8(lo_x[0], mask_and); lo[0] = vshl_u8(lo[0], mask_shift); lo[1] = vand_u8(lo_x[1], mask_and); lo[1] = vshl_u8(lo[1], mask_shift); lo[2] = vand_u8(lo_x[2], mask_and); lo[2] = vshl_u8(lo[2], mask_shift); lo[3] = vand_u8(lo_x[3], mask_and); lo[3] = vshl_u8(lo[3], mask_shift); hi[0] = vand_u8(hi_x[0], mask_and); hi[0] = vshl_u8(hi[0], mask_shift); hi[1] = vand_u8(hi_x[1], mask_and); hi[1] = vshl_u8(hi[1], mask_shift); hi[2] = vand_u8(hi_x[2], mask_and); hi[2] = vshl_u8(hi[2], mask_shift); hi[3] = vand_u8(hi_x[3], mask_and); hi[3] = vshl_u8(hi[3], mask_shift); lo[0] = vpadd_u8(lo[0], lo[0]); lo[0] = vpadd_u8(lo[0], lo[0]); lo[0] = vpadd_u8(lo[0], lo[0]); lo[1] = vpadd_u8(lo[1], lo[1]); lo[1] = vpadd_u8(lo[1], lo[1]); lo[1] = vpadd_u8(lo[1], lo[1]); lo[2] = vpadd_u8(lo[2], lo[2]); lo[2] = vpadd_u8(lo[2], lo[2]); lo[2] = vpadd_u8(lo[2], lo[2]); lo[3] = vpadd_u8(lo[3], lo[3]); lo[3] = vpadd_u8(lo[3], lo[3]); lo[3] = vpadd_u8(lo[3], lo[3]); hi[0] = vpadd_u8(hi[0], hi[0]); hi[0] = vpadd_u8(hi[0], hi[0]); hi[0] = vpadd_u8(hi[0], hi[0]); hi[1] = vpadd_u8(hi[1], hi[1]); hi[1] = vpadd_u8(hi[1], hi[1]); hi[1] = vpadd_u8(hi[1], hi[1]); hi[2] = vpadd_u8(hi[2], hi[2]); hi[2] = vpadd_u8(hi[2], hi[2]); hi[2] = vpadd_u8(hi[2], hi[2]); hi[3] = vpadd_u8(hi[3], hi[3]); hi[3] = vpadd_u8(hi[3], hi[3]); hi[3] = vpadd_u8(hi[3], hi[3]); /* Shift packed 8-bit */ lo_x[0] = vshr_n_u8(lo_x[0], 1); hi_x[0] = vshr_n_u8(hi_x[0], 1); lo_x[1] = vshr_n_u8(lo_x[1], 1); hi_x[1] = vshr_n_u8(hi_x[1], 1); lo_x[2] = vshr_n_u8(lo_x[2], 1); hi_x[2] = vshr_n_u8(hi_x[2], 1); lo_x[3] = vshr_n_u8(lo_x[3], 1); hi_x[3] = vshr_n_u8(hi_x[3], 1); /* Store the created mask to the destination vector */ vst1_lane_u8(dest + 4*j + i, lo[0], 0); vst1_lane_u8(dest + 4*j+1 + i, lo[1], 0); vst1_lane_u8(dest + 4*j+2 + i, lo[2], 0); vst1_lane_u8(dest + 4*j+3 + i, lo[3], 0); vst1_lane_u8(dest + 4*j + i + 32, hi[0], 0); vst1_lane_u8(dest + 4*j+1 + i + 32, hi[1], 0); vst1_lane_u8(dest + 4*j+2 + i + 32, hi[2], 0); vst1_lane_u8(dest + 4*j+3 + i + 32, hi[3], 0); } } } void main() { uint8_t *src = "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47" "\xcb\xff\xf1\x79\x24\x7c\xb1\x58\x69\xd2\xee\xdd\x99\x9a\x7a\x86" "\x45\x3e\x5f\xdf\xa2\x43\x41\x25\x77\xae\xfd\x22\x19\x1a\x38\x2b" "\x56\x93\xab\xc3\x61\xa8\x7d\xfc\xbb\x98\xf6\xd1\x29\xce\xe7\x58" "\x73\x4c\xd3\x12\x3f\xcf\x46\x94\xba\xfa\x49\x83\x71\x1e\x35\x5f" "\xbc\x2d\x3f\x7c\xf8\xb4\xb9\xa8\xc9\x9f\x8d\x9d\x11\xc4\xc3\x23" "\x44\x3a\x11\x4f\xf2\x41\x31\xb8\x19\xbe\xad\x72\xdc\x3a\xbc\x34" "\x53\xa7\xc6\xb3\x71\xc8\x83\x27\xb3\x45\x82\xd8\x95\x9e\x71\x92" "\x88\x4f\xdd\x66\xbf\xc5\xd6\x42\x33\x18\x33\xf7\xaf\xab\x42\x47"; size_t i; uint8_t *dest1 = calloc(512,1); uint8_t *dest2 = calloc(512,1); size_t size = 512; bitshuffle4_neon(src, dest1, size); bitunshuffle4_neon(dest1, dest2, size); for (i = 0; i < 256; i++) { assert(dest2[i] == src[i]); } free(dest1); free(dest2); }
clayne/c-blosc2
plugins/filters/ndmean/ndmean.c
<filename>plugins/filters/ndmean/ndmean.c<gh_stars>0 /* Copyright (C) 2021 The Blosc Developers http://blosc.org License: BSD 3-Clause (see LICENSE.txt) */ #include "ndmean.h" #include <stdio.h> #include <blosc2/blosc2-common.h> #include "../plugins/plugin_utils.h" static void index_unidim_to_multidim(int8_t ndim, const int64_t *shape, int64_t i, int64_t *index) { int64_t strides[NDMEAN_MAX_DIM]; strides[0] = 1; if (ndim > 1) { strides[ndim - 1] = 1; for (int j = ndim - 2; j >= 0; --j) { strides[j] = shape[j + 1] * strides[j + 1]; } } index[0] = i / strides[0]; if (ndim > 1) { for (int j = 1; j < ndim; ++j) { index[j] = (i % strides[j - 1]) / strides[j]; } } } int ndmean_encoder(const uint8_t* input, uint8_t* output, int32_t length, uint8_t meta, blosc2_cparams* cparams) { int8_t ndim; int64_t* shape = malloc(8 * sizeof(int64_t)); int32_t* chunkshape = malloc(8 * sizeof(int32_t)); int32_t* blockshape = malloc(8 * sizeof(int32_t)); uint8_t* smeta; int32_t smeta_len; if (blosc2_meta_get(cparams->schunk, "caterva", &smeta, &smeta_len) < 0) { free(shape); free(chunkshape); free(blockshape); printf("Blosc error"); return 0; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); int typesize = cparams->typesize; if ((typesize != 4) && (typesize != 8)) { free(shape); free(chunkshape); free(blockshape); fprintf(stderr, "This filter only works for float or double buffers"); return -1; } int8_t cellshape[8]; int cell_size = 1; for (int i = 0; i < 8; ++i) { if (i < ndim) { cellshape[i] = (int8_t)meta; if (cellshape[i] > blockshape[i]) { cellshape[i] = (int8_t) blockshape[i]; } cell_size *= cellshape[i]; } else { cellshape[i] = 1; } } int32_t blocksize = (int32_t) typesize; for (int i = 0; i < ndim; i++){ blocksize *= blockshape[i]; } if (length != blocksize) { free(shape); free(chunkshape); free(blockshape); printf("Length not equal to blocksize %d %d \n", length, blocksize); return -1; } uint8_t* ip = (uint8_t *) input; float* ip_float = (float *) ip; double * ip_double = (double *) ip; uint8_t* op = (uint8_t *) output; uint8_t* op_limit = op + length; int64_t cell_length; float mean_float = 0; double mean_double = 0; /* input and output buffer cannot be less than cell size */ if (length < cell_size * typesize) { free(shape); free(chunkshape); free(blockshape); printf("Incorrect length"); return 0; } uint8_t* obase = op; int64_t i_shape[NDMEAN_MAX_DIM]; for (int i = 0; i < ndim; ++i) { i_shape[i] = (blockshape[i] + cellshape[i] - 1) / cellshape[i]; } int64_t ncells = 1; for (int i = 0; i < ndim; ++i) { ncells *= i_shape[i]; } /* main loop */ int64_t pad_shape[NDMEAN_MAX_DIM]; int64_t ii[NDMEAN_MAX_DIM]; for (int cell_ind = 0; cell_ind < ncells; cell_ind++) { // for each cell index_unidim_to_multidim(ndim, i_shape, cell_ind, ii); uint32_t orig = 0; int64_t nd_aux = (int64_t) (cellshape[0]); for (int i = ndim - 1; i >= 0; i--) { orig += ii[i] * nd_aux; nd_aux *= blockshape[i]; } for (int dim_ind = 0; dim_ind < ndim; dim_ind++) { if ((blockshape[dim_ind] % cellshape[dim_ind] != 0) && (ii[dim_ind] == i_shape[dim_ind] - 1)) { pad_shape[dim_ind] = blockshape[dim_ind] % cellshape[dim_ind]; } else { pad_shape[dim_ind] = (int32_t) cellshape[dim_ind]; } } int64_t ncopies = 1; for (int i = 0; i < ndim - 1; ++i) { ncopies *= pad_shape[i]; } int64_t kk[8]; mean_float = 0; mean_double = 0; for (int copy_ind = 0; copy_ind < ncopies; ++copy_ind) { index_unidim_to_multidim((int8_t) (ndim - 1), pad_shape, copy_ind, kk); nd_aux = blockshape[ndim - 1]; int64_t ind = orig; for (int i = ndim - 2; i >= 0; i--) { ind += kk[i] * nd_aux; nd_aux *= blockshape[i]; } switch (typesize) { case 4: for (int i = 0; i < pad_shape[ndim - 1]; i++) { mean_float += ip_float[ind + i]; } break; case 8: for (int i = 0; i < pad_shape[ndim - 1]; i++) { mean_double += ip_double[ind + i]; } break; default : break; } } cell_length = ncopies * pad_shape[ndim - 1]; switch (typesize) { case 4: mean_float /= (float) cell_length; for (int i = 0; i < cell_length; i++) { memcpy(op, &mean_float, typesize); op += typesize; } break; case 8: mean_double /= (double) cell_length; for (int i = 0; i < cell_length; i++) { memcpy(op, &mean_double, typesize); op += typesize; } break; default : break; } if (op > op_limit) { free(shape); free(chunkshape); free(blockshape); printf("Output too big"); return 0; } } free(shape); free(chunkshape); free(blockshape); if((op - obase) != length) { printf("Output size must be equal to input size \n"); return 0; } return BLOSC2_ERROR_SUCCESS; } int ndmean_decoder(const uint8_t* input, uint8_t* output, int32_t length, uint8_t meta, blosc2_dparams* dparams) { blosc2_schunk *schunk = dparams->schunk; int8_t ndim; int64_t* shape = malloc(8 * sizeof(int64_t)); int32_t* chunkshape = malloc(8 * sizeof(int32_t)); int32_t* blockshape = malloc(8 * sizeof(int32_t)); uint8_t* smeta; int32_t smeta_len; if (blosc2_meta_get(schunk, "caterva", &smeta, &smeta_len) < 0) { free(shape); free(chunkshape); free(blockshape); printf("Blosc error"); return 0; } deserialize_meta(smeta, smeta_len, &ndim, shape, chunkshape, blockshape); free(smeta); int8_t cellshape[8]; int cell_size = 1; for (int i = 0; i < 8; ++i) { if (i < ndim) { cellshape[i] = (int8_t)meta; if (cellshape[i] > blockshape[i]) { cellshape[i] = (int8_t) blockshape[i]; } cell_size *= cellshape[i]; } else { cellshape[i] = 1; } } int8_t typesize = (int8_t) schunk->typesize; uint8_t* ip = (uint8_t*)input; uint8_t* ip_limit = ip + length; uint8_t* op = (uint8_t*)output; int32_t blocksize = (int32_t) typesize; for (int i = 0; i < ndim; i++){ blocksize *= blockshape[i]; } if (length != blocksize) { free(shape); free(chunkshape); free(blockshape); printf("Length not equal to blocksize \n"); return -1; } /* input and output buffer cannot be less than cell size */ if (length < cell_size * typesize) { free(shape); free(chunkshape); free(blockshape); printf("Incorrect length"); return 0; } int64_t i_shape[NDMEAN_MAX_DIM]; for (int i = 0; i < ndim; ++i) { i_shape[i] = (blockshape[i] + cellshape[i] - 1) / cellshape[i]; } int64_t ncells = 1; for (int i = 0; i < ndim; ++i) { ncells *= i_shape[i]; } /* main loop */ int64_t pad_shape[NDMEAN_MAX_DIM]; int64_t ii[NDMEAN_MAX_DIM]; int32_t ind; for (int cell_ind = 0; cell_ind < ncells; cell_ind++) { // for each cell if (ip > ip_limit) { free(shape); free(chunkshape); free(blockshape); printf("Literal copy \n"); return 0; } index_unidim_to_multidim(ndim, i_shape, cell_ind, ii); uint32_t orig = 0; int64_t nd_aux = (int64_t) (cellshape[0]); for (int i = ndim - 1; i >= 0; i--) { orig += ii[i] * nd_aux; nd_aux *= blockshape[i]; } for (int dim_ind = 0; dim_ind < ndim; dim_ind++) { if ((blockshape[dim_ind] % cellshape[dim_ind] != 0) && (ii[dim_ind] == i_shape[dim_ind] - 1)) { pad_shape[dim_ind] = blockshape[dim_ind] % cellshape[dim_ind]; } else { pad_shape[dim_ind] = (int64_t) cellshape[dim_ind]; } } int64_t ncopies = 1; for (int i = 0; i < ndim - 1; ++i) { ncopies *= pad_shape[i]; } int64_t kk[NDMEAN_MAX_DIM]; for (int copy_ind = 0; copy_ind < ncopies; ++copy_ind) { index_unidim_to_multidim((int8_t) (ndim - 1), pad_shape, copy_ind, kk); nd_aux = blockshape[ndim - 1]; ind = (int32_t) orig; for (int i = ndim - 2; i >= 0; i--) { ind += (int32_t) (kk[i] * nd_aux); nd_aux *= blockshape[i]; } memcpy(&op[ind * typesize], ip, pad_shape[ndim - 1] * typesize); ip += pad_shape[ndim - 1] * typesize; } } ind += (int32_t) pad_shape[ndim - 1]; free(shape); free(chunkshape); free(blockshape); if (ind != (int32_t) (blocksize / typesize)) { printf("Output size is not compatible with embedded blockshape ind %d %d \n", ind, (blocksize / typesize)); return 0; } return BLOSC2_ERROR_SUCCESS; }
npisanti/np-miscela
miscela/src/Layer.h
<gh_stars>1-10 #pragma once #include "ofMain.h" #include "DotFrag.h" #include "np-pixelscript.h" namespace np{ namespace miscela { class Layer{ public: Layer(); void load( std::string path ); void render( ofFbo & fbo ); void setControlX( float value ); void setControlY( float value ); void setButtonA( bool value ); void setButtonB( bool value ); void setColorA( ofColor color ); void setColorB( ofColor color ); void setSpeed( float value ); void setModulation( float value ); void setTime( float value ); bool isFragment(){ return mode==0; } bool requiresClear(){ return mode==0; } void draw( int x, int y ); int getWidth() const { return width; }; int getHeight() const { return height; }; private: int mode; np::miscela::DotFrag frag; ofImage image; ofVideoPlayer video; np::PixelScript uscript; bool loaded; int width; int height; }; }}
npisanti/np-miscela
miscela/src/Combination.h
#pragma once #include "ofMain.h" #include "Layer.h" namespace np{ namespace miscela { class Combination { public: void setup( int w, int h, int downsample=1, int multisampling=0 ); void clear(); void add( std::string path ); void update(); void resize( int w, int h ); void setControlX( float value ); void setControlY( float value ); void setButtonA( bool value ); void setButtonB( bool value ); void setColorA( ofColor color ); void setColorB( ofColor color ); void setSpeed( float value ); void setModulation( float value ); void setTime( float value ); void draw( int x, int y ){ fbo.draw( x, y, fbo.getWidth()*downsample, fbo.getHeight()*downsample ); } std::vector<Layer> layers; ofFbo fbo; private: int multisampling; int downsample; }; }}
npisanti/np-miscela
miscela/src/ofApp.h
<gh_stars>1-10 #pragma once #include "ofMain.h" #include "ofxGui.h" #include "Combination.h" #include "np-analyzer.h" #define OVERSAMPLING 0 class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void exit(); void keyPressed(int key); void keyReleased(int key); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void xyControl( float x, float y ); np::miscela::Combination combo; std::vector<std::string> paths; float mod; bool bResize; int resizeCounter; bool bDrawGui; ofxPanel gui; ofParameter<float> speed; ofParameter<float> controlX; ofParameter<float> controlY; ofParameter<bool> buttonA; ofParameter<bool> buttonB; ofParameter<ofColor> colorA; ofParameter<ofColor> colorB; ofParameter<bool> useCamTexture; void onUseCamTexture( bool & value ); void openCam( int index, int w, int h ); ofVideoGrabber cam; np::Analyzer analyzer; ofParameterGroup audioMap; ofParameter<float> lowThreshold; ofParameter<float> highThreshold; ofParameter<float> audioMeter; ofParameter<float> modMeter; ofParameter<float> audio2speed; bool bSave; ofParameter<int> saveFrames; ofParameter<int> saveCountDown; ofParameter<int> saveStart; int saveCounter; bool bShowFrameRate; bool bShowCursor; int downsample; int camMode; int camID; int camW; int camH; float framerate; int width; int height; bool resizable; float freqLow; float freqHigh; };
npisanti/np-miscela
miscela/src/SandBox.h
<reponame>npisanti/np-miscela #pragma once #include "ofMain.h" namespace np{ namespace miscela { class SandBox{ public: SandBox(); ofParameter<float> controlX; ofParameter<float> controlY; ofParameter<bool> buttonA; ofParameter<bool> buttonB; ofParameter<ofColor> colorA; ofParameter<ofColor> colorB; ofParameter<float> modulation; }; }}
npisanti/np-miscela
miscela/src/DotFrag.h
#pragma once #include "ofMain.h" #include "dotfrag/Live.h" #include "SandBox.h" namespace np { namespace miscela { class DotFrag : public SandBox, public ofx::dotfrag::Live { public: DotFrag(){ timewarp(); pingpong(); uniform( controlX, "u_control_x" ); uniform( controlY, "u_control_y" ); uniform( buttonA, "u_button_a" ); uniform( buttonB, "u_button_b" ); uniform( colorA, "u_color_a" ); uniform( colorB, "u_color_b" ); uniform( modulation.set("modulation", 0.0f, 0.0f, 1.0f), "u_modulation" ); } }; }} // end namespaces
keshavgupta21/pynq_api_cpp
src/pynq_api.c
/* * BSD 3-Clause License * * Copyright (c) 2019, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include <byteswap.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/time.h> #include <fcntl.h> #include <dirent.h> #include <sys/utsname.h> #include "pynq_api.h" #include "libxlnk_cma.h" // These three definitions are used for writing the bitstream payload to the PL and launching it #define BS_FPGA_MAN_FLAGS "/sys/class/fpga_manager/fpga0/flags" #define BS_FPGA_MAN "/sys/class/fpga_manager/fpga0/firmware" #define FIRMWARE_PATH_PREFIX "/lib/firmware/" // Used for creating memory windows #define MEMORY_DEV_PATH "/dev/mem" // Location of GPIO interfaces #define GPIO_PATH "/sys/class/gpio" // Used for handling interrupts raised by the PLS via the UIO interface #define INTERRUPTS_FILE "/proc/interrupts" #define UIO_DESCRIPTION_PATH "/sys/class/uio" #define UIO_PATH "/dev" // Number of bytes to read at a time when we load in the raw bitstream file #define READ_CHUNK_SIZE 1024 // Definitions below here are specific to the Zynq 7-Series PS and PL clocks #define ZYNQ_SERIES_7_IDENTIFIER "armv7l" #define SLCR_BASE_ADDRESS 0xF8000000 #define ARM_CLK_CTRL_OFFSET 0x120 #define ARM_PLL_CTRL_OFFSET 0x100 #define PL_FCLK0_CTRL_OFFSET 0x170 #define PL_FCLK0_CTRL_SPACING 0x10 #define DEFAULT_SRC_CLK_MHZ 50.0 void _xlnk_reset(); static int checkMachineType(); static int getSrcClkMHZ(PYNQ_REGISTER*, size_t, float*); static int enable_uio(PYNQ_UIO*); static void pullRaisedIRQs(PYNQ_AXI_INTERRUPT_CONTROLLER*); static void appendOrInsertRaisedInterrupt(PYNQ_AXI_INTERRUPT_CONTROLLER*, int); static struct raised_interrupt_struct * findRaisedInterruptStructure(PYNQ_AXI_INTERRUPT_CONTROLLER*, int); static char * get_device_path(char*); static char * get_uio_irq_devname(int); static int issueDMATransfer(PYNQ_AXI_DMA*, PYNQ_SHARED_MEMORY*, size_t, size_t, AXI_DMA_DIRECTION); static int startDMAChannel(PYNQ_AXI_DMA*, AXI_DMA_DIRECTION); static int stopDMAChannel(PYNQ_AXI_DMA*, AXI_DMA_DIRECTION); static int isDMAChannelRunning(PYNQ_AXI_DMA*, AXI_DMA_DIRECTION); static int isDMAChannelIdle(PYNQ_AXI_DMA*, AXI_DMA_DIRECTION); static char * getBaseNameFromFile(char*); static char * getBinNameFromBit(char*); static char * extractBitstreamPayload(char*, int*); static void extractBitstreamInfo(char*, PYNQ_BITSTREAM_INFO*); static char * readRawBitfile(char*); static void freeHeader(PYNQ_BITSTREAM_INFO*); /** * Returns the time in microseconds since the epoch */ unsigned long long PYNQ_Wtime() { struct timeval time_val; gettimeofday(&time_val, NULL); return time_val.tv_sec * 1000000 + time_val.tv_usec; } /** * Opens an HLS block to then interact with this. This is a thin layer of abstraction over the HLS memory mapped * interface and assumes the ap_ctrl_hs protocol. The width is the size of memory window to open on the HLS block * as many implementations also pass arguments via the control bus */ int PYNQ_openHLS(PYNQ_HLS * state, size_t address, size_t width) { return PYNQ_createMMIOWindow(&(state->mmio_window), address, width); } /** * Starts execution of an HLS block */ int PYNQ_startHLS(PYNQ_HLS * state) { char byte_command=1; return PYNQ_writeMMIO(&(state->mmio_window), &byte_command, 0x0, sizeof(char)); } /** * Tests whether an HLS block has completed execution or not. More specifically whether an HLS * block is idle or not (as we also assume that 0x00 status marks completion.) This completion * is written out into the flag argument provided */ int PYNQ_testHLSCompleted(PYNQ_HLS * state, int * flag) { char byte_status; if (!PYNQ_readMMIO(&(state->mmio_window), &byte_status, 0x0, sizeof(char))) return PYNQ_ERROR; *flag = byte_status == 4 || byte_status == 6 || byte_status == 0; return PYNQ_SUCCESS; } /** * Waits for an HLS kernel to complete (or more accurately for an HLS kernel to be idle) */ int PYNQ_waitForHLS(PYNQ_HLS * state) { int isFinished=0; while (!isFinished) { if(!PYNQ_testHLSCompleted(state, &isFinished)) return PYNQ_ERROR; } return PYNQ_SUCCESS; } /** * Writes some data of a specified size to some offset in the HLS block. This is just a (very) thin * layer of abstraction over the memory mapped interface */ int PYNQ_writeToHLS(PYNQ_HLS * state, void * data, size_t offset, size_t size) { return PYNQ_writeMMIO(&(state->mmio_window), data, offset, size); } /** * Reads some data of a specified size to some offset from the HLS block. This is just a (very) thin * layer of abstraction over the memory mapped interface */ int PYNQ_readFromHLS(PYNQ_HLS * state, void * data, size_t offset, size_t size) { return PYNQ_readMMIO(&(state->mmio_window), data, offset, size); } /** * Closes the interaction with an HLS block (note that this has no impact on the block itself, just the * host connection to the block.) */ int PYNQ_closeHLS(PYNQ_HLS * state) { return PYNQ_closeMMIOWindow(&(state->mmio_window)); } /** * Retrieves the CPU clock frequency in Mhz and returns this via the freq flag argument */ int PYNQ_getCPUClockFreq(float * freq) { if (!checkMachineType()) return PYNQ_ERROR; PYNQ_REGISTER reg; if (!PYNQ_openRegister(&reg, SLCR_BASE_ADDRESS, 65536)) return PYNQ_ERROR; unsigned int arm_clk_odiv, pll_fbdiv; if (!PYNQ_readRegisterRange(&reg, ARM_CLK_CTRL_OFFSET, 8, 13, &arm_clk_odiv)) return PYNQ_ERROR; if (!PYNQ_readRegisterRange(&reg, ARM_PLL_CTRL_OFFSET, 12, 18, &pll_fbdiv)) return PYNQ_ERROR; *freq=(DEFAULT_SRC_CLK_MHZ * pll_fbdiv) / arm_clk_odiv; return PYNQ_closeRegister(&reg); } /** * Retrieves the clock frequency of one of the four PL clocks as specified by the clock index * argument and writes this into the freq argument */ int PYNQ_getPLClockFreq(unsigned int clock_index, float * freq) { if (!checkMachineType()) return PYNQ_ERROR; if (clock_index >= 4) { fprintf(stderr, "Clock index is 0 to 3 on the Zynq, not %d\n", clock_index); return PYNQ_ERROR; } PYNQ_REGISTER reg; if (!PYNQ_openRegister(&reg, SLCR_BASE_ADDRESS, 65536)) return PYNQ_ERROR; size_t offset=PL_FCLK0_CTRL_OFFSET + (PL_FCLK0_CTRL_SPACING * clock_index); float src_clk_mhz; if (!getSrcClkMHZ(&reg, offset, &src_clk_mhz)) return PYNQ_ERROR; unsigned int pl_clk_odiv0, pl_clk_odiv1; if (!PYNQ_readRegisterRange(&reg, offset, 20, 25, &pl_clk_odiv0)) return PYNQ_ERROR; if (!PYNQ_readRegisterRange(&reg, offset, 8, 13, &pl_clk_odiv1)) return PYNQ_ERROR; *freq=src_clk_mhz / (pl_clk_odiv0 * pl_clk_odiv1); return PYNQ_closeRegister(&reg); } /** * Sets the clock frequency of one of the four PL clocks as specified by the clock index. The * caller must provide the frequency along with either div0 or div1. */ int PYNQ_setPLClockFreq(unsigned int clock_index, float * freq, int * div0, int *div1) { if (!checkMachineType()) return PYNQ_ERROR; if (clock_index >= 4) { fprintf(stderr, "Clock index is 0 to 3 on the Zynq, not %d\n", clock_index); return PYNQ_ERROR; } if (div0 == NULL && div1 == NULL) { fprintf(stderr, "Must provide either div0 or div1 when setting the clock\n"); return PYNQ_ERROR; } PYNQ_REGISTER reg; if (!PYNQ_openRegister(&reg, SLCR_BASE_ADDRESS, 65536)) return PYNQ_ERROR; size_t offset=PL_FCLK0_CTRL_OFFSET + (PL_FCLK0_CTRL_SPACING * clock_index); float src_clk_mhz; if (!getSrcClkMHZ(&reg, offset, &src_clk_mhz)) return PYNQ_ERROR; int my_d0, my_d1; if (div0 != NULL && div1 == NULL) { my_d0=*div0; my_d1 = src_clk_mhz / *freq / my_d0; } else if (div0 == NULL && div1 != NULL) { my_d1=*div1; my_d0 = src_clk_mhz / *freq / my_d1; } else { my_d0=*div0; my_d1=*div1; } unsigned int pl_clk_odiv0, pl_clk_odiv1; if (!PYNQ_readRegisterRange(&reg, offset, 20, 25, &pl_clk_odiv0)) return PYNQ_ERROR; if (!PYNQ_readRegisterRange(&reg, offset, 8, 13, &pl_clk_odiv1)) return PYNQ_ERROR; if (my_d0 <= 0 || my_d0 > ((1 << pl_clk_odiv0) - 1)) { fprintf(stderr, "Frequency divider 0 value of '%d' out of range\n", my_d0); return PYNQ_ERROR; } if (my_d1 <= 0 || my_d1 > ((1 << pl_clk_odiv1) - 1)) { fprintf(stderr, "Frequency divider 1 value of '%d' out of range\n", my_d1); return PYNQ_ERROR; } if (!PYNQ_setRegisterRange(&reg, offset, 20, 25, &my_d0)) return PYNQ_ERROR; if (!PYNQ_setRegisterRange(&reg, offset, 8, 13, &my_d1)) return PYNQ_ERROR; return PYNQ_closeRegister(&reg); } /** * Opens a register for interaction at a specific address and width */ int PYNQ_openRegister(PYNQ_REGISTER* state, size_t address, size_t width) { return PYNQ_createMMIOWindow(&(state->mmio_window), address, width); } /** * Reads the register at a specific offset (address) and bit index. This bit is then returned in * the data argument */ int PYNQ_readRegister(PYNQ_REGISTER* state, size_t address, int index, unsigned int * data) { unsigned int read_data; if (PYNQ_readMMIO(&(state->mmio_window), &read_data, address, sizeof(unsigned int)) == PYNQ_ERROR) { return PYNQ_ERROR; } unsigned int mask = 1 << index; *data=(read_data & mask) >> index; return PYNQ_SUCCESS; } /** * Reads a range of bits from a 32 bit window on the register at offset address. These read bits must be contiguous between * the start_index and stop_index, and are written into the data argument */ int PYNQ_readRegisterRange(PYNQ_REGISTER* state, size_t address, int start_index, int stop_index, unsigned int * data) { unsigned int read_data; if (PYNQ_readMMIO(&(state->mmio_window), &read_data, address, sizeof(unsigned int)) == PYNQ_ERROR) { return PYNQ_ERROR; } if (start_index >= stop_index) { unsigned int mask = ((1 << (start_index - stop_index + 1)) - 1) << stop_index; *data=(read_data & mask) >> stop_index; } else { unsigned int width = stop_index - start_index + 1; unsigned int mask = ((1 << width) - 1) << start_index; *data=(read_data & mask) >> start_index; } return PYNQ_SUCCESS; } /** * Sets the bit value of a register at offset address. The bit index to write to is provided as is the data itself to write at that bit */ int PYNQ_setRegister(PYNQ_REGISTER* state, size_t address, int index, unsigned int * data) { unsigned int read_data, write_data; if (PYNQ_readMMIO(&(state->mmio_window), &read_data, address, sizeof(unsigned int)) == PYNQ_ERROR) { return PYNQ_ERROR; } unsigned int mask = 1 << index; write_data=(read_data & ~mask) | (*data << index); return PYNQ_writeMMIO(&(state->mmio_window), &write_data, 0x00, sizeof(unsigned int)); } /** * Sets the bit values of a register between a range of a 32 bit window at offset address. The start_index to stop_index are * assumed to be contiguous and the data provided in the data argument */ int PYNQ_setRegisterRange(PYNQ_REGISTER* state, size_t address, int start_index, int stop_index, unsigned int * data) { unsigned int read_data, write_data; if (PYNQ_readMMIO(&(state->mmio_window), &read_data, address, sizeof(unsigned int)) == PYNQ_ERROR) { return PYNQ_ERROR; } unsigned int count = start_index >= stop_index ? start_index-stop_index+1 : stop_index-start_index+1; unsigned int shift = start_index >= stop_index ? stop_index : start_index; unsigned int mask = ((1 << count) - 1) << shift; write_data=(read_data & ~mask) | (*data << shift); return PYNQ_writeMMIO(&(state->mmio_window), &write_data, 0x00, sizeof(unsigned int)); } /** * Closes a register */ int PYNQ_closeRegister(PYNQ_REGISTER* state) { return PYNQ_closeMMIOWindow(&(state->mmio_window)); } /** * Opens an AXI interrupt controller for interaction at a specific base address. Whilst this isn't * strictly speaking part of the core ZYNQ eco-system, this is a very common IP block and hence we support it */ int PYNQ_openInterruptController(PYNQ_AXI_INTERRUPT_CONTROLLER * state, size_t base_address) { PYNQ_createMMIOWindow(&(state->mmio_window), base_address, 128); state->raised_interrupt_head=NULL; state->enabled_hw_interrupts=0; unsigned int command=0x00; //disable all interrupt lines by default (enabled on an interrupt by interrupt basis) PYNQ_writeMMIO(&(state->mmio_window), &command, 0x8, sizeof(unsigned int)); return PYNQ_SUCCESS; } /** * Registers the tracking of an interrupt by the AXI interrupt controller, note that the IRQ number is the number as the * controller sees it and bares no relationship to the IRQ number at the ZYNQ processing system. The caller can specify whether * the raising of this interrupt will generate a hardware interrupt on the irq pin of the controller. */ int PYNQ_registerInterrupt(PYNQ_AXI_INTERRUPT_CONTROLLER * state, int irq_number, int generate_hw_interrupt) { struct raised_interrupt_struct * interrupt = findRaisedInterruptStructure(state, irq_number); if (interrupt == NULL) { interrupt=(struct raised_interrupt_struct *) malloc(sizeof(struct raised_interrupt_struct)); interrupt->irq=irq_number; interrupt->number=0; interrupt->active_waiting=0; interrupt->next=state->raised_interrupt_head; state->raised_interrupt_head=interrupt; } if (!interrupt->active_waiting) { if (generate_hw_interrupt) { int new_hw_interrupts=state->enabled_hw_interrupts | (1 << irq_number); if (new_hw_interrupts != state->enabled_hw_interrupts) { state->enabled_hw_interrupts=new_hw_interrupts; PYNQ_writeMMIO(&(state->mmio_window), &new_hw_interrupts, 0x8, sizeof(unsigned int)); } } interrupt->active_waiting=1; unsigned int irq_bit=1 << irq_number; PYNQ_writeMMIO(&(state->mmio_window), &irq_bit, 0x10, sizeof(unsigned int)); unsigned int enable_global_interupts=3; PYNQ_writeMMIO(&(state->mmio_window), &enable_global_interupts, 0x1C, sizeof(unsigned int)); } } /** * Tests whether an interrupt has been raised at the AXI interrupt controller, and this is written into the * flag argument, with the IRQ number being dictated by the controller and not the ZYNQ PS. Note that the * interrupt must have been registered before it is tested for. Also in a single test a number of interrupts might * be detected and if so they will be stored for future testing by other callers. */ int PYNQ_testForInterrupt(PYNQ_AXI_INTERRUPT_CONTROLLER * state, int irq_number, int * flag) { struct raised_interrupt_struct * interrupt = findRaisedInterruptStructure(state, irq_number); if (interrupt != NULL) { if (interrupt->number > 0) { interrupt->number--; *flag=1; return PYNQ_SUCCESS; } } else { fprintf(stderr, "You need to register an interrupt with IRQ %d before testing or waiting for it\n", irq_number); return PYNQ_ERROR; } pullRaisedIRQs(state); if (interrupt->number > 0) { interrupt->number--; *flag=1; } else { *flag=0; } return PYNQ_SUCCESS; } /** * Waits for an interrupt to be raised at the AXI interrupt controller based on the IRQ number which is * dictated by the controller and not the Zynq PS. */ int PYNQ_waitForInterrupt(PYNQ_AXI_INTERRUPT_CONTROLLER * state, int irq_number) { int flag=0; while (flag == 0) { PYNQ_testForInterrupt(state, irq_number, &flag); } return PYNQ_SUCCESS; } /** * Closes the connection to the interrupt controller (although this will still function uneffected) * and frees up associated memory. */ int PYNQ_closeInterruptController(PYNQ_AXI_INTERRUPT_CONTROLLER * state) { PYNQ_closeMMIOWindow(&(state->mmio_window)); struct raised_interrupt_struct * head=state->raised_interrupt_head; while (head != NULL) { struct raised_interrupt_struct * p=head; head=head->next; free(p); } return PYNQ_SUCCESS; } /** * Opens a Userspace I/O (UIO) interface based on the provided IRQ number which is the number as seen by the * Zynq PS. */ int PYNQ_openUIO(PYNQ_UIO * state, int irq) { char * dev_name=get_uio_irq_devname(irq + 61); if (dev_name == NULL) return PYNQ_ERROR; state->filename=get_device_path(dev_name); free(dev_name); state->active=0; state->irq=irq; return PYNQ_SUCCESS; } /** * Waits for the UIO to detect the raised interrupt and returns the interrupt count (i.e. the sequence number * of the raised interrupt which can be useful to ensure the code has not missed interrupts) */ int PYNQ_waitForUIO(PYNQ_UIO * state, int * flag) { if (!state->active) { if (enable_uio(state) == PYNQ_ERROR) return PYNQ_ERROR; } int f = open(state->filename, O_RDONLY); if (f == -1) { fprintf(stderr, "Error opening UIO file '%s'\n", state->filename); return PYNQ_ERROR; } int data; int code=read(f, &data, sizeof(int)); if (code != sizeof(int)) { fprintf(stderr, "Expected to read 32 bit interrupt from '%s' but got %d bytes\n", state->filename, code); return PYNQ_ERROR; } close(f); state->active=0; *flag=data; return PYNQ_SUCCESS; } /** * Checks the UIO interface for whether an interrupt has been raised or not. If not then -1 is returned * in the flag, otherwise the flag contains the interrupt count (i.e. the sequence number * of the raised interrupt which can be useful to ensure the code has not missed interrupts) */ int PYNQ_checkForUIO(PYNQ_UIO * state, int * flag) { if (!state->active) { if (enable_uio(state) == PYNQ_ERROR) return PYNQ_ERROR; } int f = open(state->filename, O_RDONLY | O_NONBLOCK); if (f == -1) { fprintf(stderr, "Error opening UIO file '%s'\n", state->filename); return PYNQ_ERROR; } int data; int code=read(f, &data, sizeof(int)); close(f); if (code == sizeof(int)) { state->active=0; *flag=data; } else if (code == -1) { *flag=-1; } else { fprintf(stderr, "Expected to read 32 bit interrupt from '%s' or none, but got %d bytes\n", state->filename, code); return PYNQ_ERROR; } return PYNQ_SUCCESS; } /** * Closes the UIO interface, note that this is just the connection to that interface in this user code and * does not effect the raising of interrupts on the IRQ by the PL or other codes listening for interrupts via * that same UIO */ int PYNQ_closeUIO(PYNQ_UIO * state) { free(state->filename); return PYNQ_SUCCESS; } /** * This opens the DMA based on the AXI DMA IP block at the specified base address. Whilst this is not a core * part of the Zynq eco-system it is a very popular IP block and-so abstracting it is useful. The block works by containing * two separate channels, one for writing and one for reading. This call starts the channels. */ int PYNQ_openDMA(PYNQ_AXI_DMA * state, size_t base_address) { PYNQ_createMMIOWindow(&(state->mmio_window), base_address, 128); state->write_channel_offset=0x00; state->read_channel_offset=0x30; state->first_transfer[AXI_DMA_WRITE]=1; state->first_transfer[AXI_DMA_READ]=1; state->interrupt_mode=0; if (startDMAChannel(state, AXI_DMA_WRITE) == PYNQ_ERROR) return PYNQ_ERROR; if (startDMAChannel(state, AXI_DMA_READ) == PYNQ_ERROR) return PYNQ_ERROR; return PYNQ_SUCCESS; } /** * Sets the interrupt mode of the DMA transfer, by default no interrupt will be raised when transfers complete but this can be * changed by calling into this function. Note that this call will stop and restart the channels in the new mode, so you should * not do this whilst a transfer is in progress */ int PYNQ_setDMATransferInterruptMode(PYNQ_AXI_DMA * state, int interrupt_mode) { if (interrupt_mode != state->interrupt_mode) { state->interrupt_mode=interrupt_mode; if (stopDMAChannel(state, AXI_DMA_WRITE) == PYNQ_ERROR) return PYNQ_ERROR; if (stopDMAChannel(state, AXI_DMA_READ) == PYNQ_ERROR) return PYNQ_ERROR; if (startDMAChannel(state, AXI_DMA_WRITE) == PYNQ_ERROR) return PYNQ_ERROR; if (startDMAChannel(state, AXI_DMA_READ) == PYNQ_ERROR) return PYNQ_ERROR; } return PYNQ_SUCCESS; } /** * Starts a DMA transfer from some location in shared (DRAM) memory at the data_offset, in a specific direction (either writing * or reading) */ int PYNQ_issueDMATransfer(PYNQ_AXI_DMA * state, PYNQ_SHARED_MEMORY * sm_state, size_t data_offset, size_t length, AXI_DMA_DIRECTION direction) { if (direction != AXI_DMA_WRITE && direction != AXI_DMA_READ) { fprintf(stderr, "You must supply either AXI_DMA_WRITE or AXI_DMA_READ as the transfer DMA direction\n"); return PYNQ_ERROR; } return issueDMATransfer(state, sm_state, data_offset, length, direction); } /** * Writes some data to the PL via the DMA engine. The data is located in the provided shared memory at the specified offset of * length provided. */ int PYNQ_writeDMA(PYNQ_AXI_DMA * state, PYNQ_SHARED_MEMORY * sm_state, size_t offset, size_t length) { return issueDMATransfer(state, sm_state, offset, length, AXI_DMA_WRITE); } /** * Reads some data from the PL via the DMA engine. The data is copied into the provided shared memory at the specified offset of * length provided. */ int PYNQ_readDMA(PYNQ_AXI_DMA * state, PYNQ_SHARED_MEMORY * sm_state, size_t offset, size_t length) { return issueDMATransfer(state, sm_state, offset, length, AXI_DMA_READ); } /** * Tests whether DMA has completed and writes this into the provided flag. Note that this follows the interrupt less approach, even * if the user enabled interrupts */ int PYNQ_testForDMAComplete(PYNQ_AXI_DMA * state, AXI_DMA_DIRECTION direction, int * flag) { if (direction != AXI_DMA_WRITE && direction != AXI_DMA_READ) { fprintf(stderr, "You must supply either AXI_DMA_WRITE or AXI_DMA_READ as the transfer DMA direction\n"); return PYNQ_ERROR; } if (!isDMAChannelRunning(state, AXI_DMA_WRITE)) { fprintf(stderr, "Error testing DMA completion status as engine is not running\n"); return PYNQ_ERROR; } *flag=!isDMAChannelIdle(state, direction); return PYNQ_SUCCESS; } /** * Waits fo DMA to complete in a specified direction */ int PYNQ_waitForDMAComplete(PYNQ_AXI_DMA * state, AXI_DMA_DIRECTION direction) { if (direction != AXI_DMA_WRITE && direction != AXI_DMA_READ) { fprintf(stderr, "You must supply either AXI_DMA_WRITE or AXI_DMA_READ as the transfer DMA direction\n"); return PYNQ_ERROR; } if (!isDMAChannelRunning(state, AXI_DMA_WRITE)) { fprintf(stderr, "Error waiting for DMA completion as engine is not running"); return PYNQ_ERROR; } while (!isDMAChannelIdle(state, direction)); return PYNQ_SUCCESS; } /** * Closes the DMA transfer connection and stops the channels */ int PYNQ_closeDMA(PYNQ_AXI_DMA * state) { if (stopDMAChannel(state, AXI_DMA_WRITE) == PYNQ_ERROR) return PYNQ_ERROR; if (stopDMAChannel(state, AXI_DMA_READ) == PYNQ_ERROR) return PYNQ_ERROR; return PYNQ_closeMMIOWindow(&(state->mmio_window)); } /** * Allocates a portion of DRAM to be shared memory that the PL can also interact with. Whilst the PL can see * the DRAM memory, one must be careful as virtual memory can not be used as normal - instead the memory must be * physically pinned. This calls into the cma library which maintains its own memory allocation state. Upon code * termination the cma library does not clean up memory, therefore if there is not enough memory then the link can * reset to free all memory and retry, although you might not want this and hence it is an option. * * Once allocated we assume the caller will then use the pointer and physical_address members of the PYNQ_SHARED_MEMORY * type directly in their code */ int PYNQ_allocatedSharedMemory(PYNQ_SHARED_MEMORY * state, size_t length, int allow_reset) { unsigned int page_size=sysconf(_SC_PAGESIZE); if (length >= page_size*cma_pages_available()) { // If we haven't got enough shared memory then first reset the link which should free up any previously allocated but not freed memory if (allow_reset) _xlnk_reset(); // Now recheck how much shared memory there is and error if we don't have enough available if (length >= page_size*cma_pages_available()) { fprintf(stderr, "Unable to allocate shared memory as %d bytes is requested but only %d bytes available\n", length, page_size*cma_pages_available()); return PYNQ_ERROR; } } state->pointer=cma_alloc(length, 0); if (state->pointer == NULL) { fprintf(stderr, "Unable to allocate shared memory of %d bytes, allocator returned error\n", length); return PYNQ_ERROR; } state->physical_address=cma_get_phy_addr(state->pointer); return PYNQ_SUCCESS; } /** * Frees the allocated shared memory */ int PYNQ_freeSharedMemory(PYNQ_SHARED_MEMORY * state) { cma_free(state->pointer); return PYNQ_SUCCESS; } /** * Creates an MMIO window at a specific base address of a provided size */ int PYNQ_createMMIOWindow(PYNQ_MMIO_WINDOW * state, size_t address_base, size_t length) { // Align the base address with the pages state->virt_base = address_base & ~(sysconf(_SC_PAGESIZE) - 1); state->virt_offset = address_base - state->virt_base; state->length=length; state->address_base=address_base; state->file_handle=open(MEMORY_DEV_PATH, O_RDWR | O_SYNC); if (state->file_handle == -1) { fprintf(stderr, "Unable to open '%s' to create memory window", MEMORY_DEV_PATH); return PYNQ_ERROR; } state->buffer=mmap(NULL, length+state->virt_offset, PROT_READ | PROT_WRITE, MAP_SHARED, state->file_handle, state->virt_base); if (state->buffer == MAP_FAILED) { fprintf(stderr, "Mapping memory to MMIO region failed"); return PYNQ_ERROR; } return PYNQ_SUCCESS; } /** * Closes an MMIO window that we have previously created */ int PYNQ_closeMMIOWindow(PYNQ_MMIO_WINDOW * state) { close(state->file_handle); return PYNQ_SUCCESS; } /** * Writes some data, of provided size to the specified offset in the memory window */ int PYNQ_writeMMIO(PYNQ_MMIO_WINDOW * state, void * data, size_t offset, size_t size_data) { memcpy(&(state->buffer[offset]), data, size_data); return PYNQ_SUCCESS; } /** * Reads some data, of provided size to the specified offset from the memory window */ int PYNQ_readMMIO(PYNQ_MMIO_WINDOW * state, void * data, size_t offset, size_t size_data) { memcpy(data, &(state->buffer[offset]), size_data); return PYNQ_SUCCESS; } /** * Opens a General Purpose I/O (GPIO) port at a specified index with direction provided */ int PYNQ_openGPIO(PYNQ_GPIO * state, int index, GPIO_DIRECTION direction) { state->index=index; state->direction=direction; char path[150], export_path[150]; sprintf(path, "%s/gpio%d", GPIO_PATH, index); if (access(path, F_OK) == -1 ) { sprintf(export_path, "%s/export", GPIO_PATH); FILE * create_handle=fopen(export_path, "w"); if (create_handle == NULL) { fprintf(stderr, "Can not open '%s' to create GPIO\n", export_path); return PYNQ_ERROR; } fprintf(create_handle, "%d", index); fclose(create_handle); } char f_name[150]; sprintf(f_name,"%s/direction", path); FILE * handle=fopen(f_name, "w"); if (handle == NULL) { fprintf(stderr, "Can not open '%s' to create GPIO\n", f_name); return PYNQ_ERROR; } if (direction == GPIO_OUT) { fprintf(handle, "out"); } else if (direction == GPIO_IN) { fprintf(handle, "in"); } else { fclose(handle); fprintf(stderr, "Must either supply GPIO_OUT or GPIO_IN as GPIO direction in open call\n"); return PYNQ_ERROR; } fclose(handle); state->filename=(char*) malloc(strlen(path) + 7); sprintf(state->filename,"%s/value", path); return PYNQ_SUCCESS; } /** * Closes an opened GPIO port */ int PYNQ_closeGPIO(PYNQ_GPIO * state) { char unexport_path[150]; sprintf(unexport_path, "%s/unexport", GPIO_PATH); free(state->filename); FILE * handle=fopen(unexport_path, "w"); if (handle == NULL) { fprintf(stderr, "Can not open '%s' to close GPIO\n", unexport_path); return PYNQ_ERROR; } fprintf(handle, "%d", state->index); fclose(handle); return PYNQ_SUCCESS; } /** * Writes some data, val, to the GPIO that we have previously opened */ int PYNQ_writeGPIO(PYNQ_GPIO * state, int * val) { FILE * file_handle=fopen(state->filename, state->direction==GPIO_OUT ? "w" : "r"); if (file_handle == NULL) { fprintf(stderr, "Can not open '%s' to write to GPIO\n", state->filename); return PYNQ_ERROR; } fprintf(file_handle, "%d", *val); fclose(file_handle); return PYNQ_SUCCESS; } /** * Reads some data, val, from the GPIO that we have previously opened */ int PYNQ_readGPIO(PYNQ_GPIO * state, int * val) { FILE * file_handle=fopen(state->filename, state->direction==GPIO_OUT ? "w" : "r"); if (file_handle == NULL) { fprintf(stderr, "Can not open '%s' to read from GPIO\n", state->filename); return PYNQ_ERROR; } *val=fgetc(file_handle); fclose(file_handle); return PYNQ_SUCCESS; } /** * Loads the bitstream with name and location, bitstream_name, onto the PL and activates it. */ int PYNQ_loadBitstream(char * bitstream_name) { int bitstream_payload_length; char * bitstream_payload=extractBitstreamPayload(bitstream_name, &bitstream_payload_length); char * base_name=getBaseNameFromFile(bitstream_name); char * binfile_name=getBinNameFromBit(base_name); char firmware_path[strlen(binfile_name) + strlen(FIRMWARE_PATH_PREFIX)+1]; sprintf(firmware_path, "%s%s", FIRMWARE_PATH_PREFIX, binfile_name); FILE * f =fopen(firmware_path, "wb"); if (f == NULL) { fprintf(stderr, "Can not open firmware file '%s'\n", firmware_path); free(bitstream_payload); free(binfile_name); return PYNQ_ERROR; } fwrite(bitstream_payload, sizeof(char), bitstream_payload_length, f); fclose(f); free(bitstream_payload); FILE *fptr = fopen(BS_FPGA_MAN_FLAGS, "w"); if (fptr == NULL) { fprintf(stderr, "Can not open man flags file '%s'\n", BS_FPGA_MAN_FLAGS); free(binfile_name); return PYNQ_ERROR; } fprintf(fptr, "0"); fclose(fptr); fptr = fopen(BS_FPGA_MAN, "w"); if (fptr == NULL) { fprintf(stderr, "Can not open man file '%s'\n", BS_FPGA_MAN); return PYNQ_ERROR; } fprintf(fptr, "%s", binfile_name); fclose(fptr); free(binfile_name); return PYNQ_SUCCESS; } /** * Extracs information from the bit stream, bitstream_name, into the header type. This contains both the header information * and payload data. */ int PYNQ_extractBitstreamInfo(PYNQ_BITSTREAM_INFO * bitstream_header, char * bitstream_name) { extractBitstreamInfo(bitstream_name, bitstream_header); return PYNQ_SUCCESS; } /** * Frees the memory associated with bitstream information type that was previously used to extract the information from * the bit stream into. */ int PYNQ_freeBitstreamInfo(PYNQ_BITSTREAM_INFO * header) { free(header->data); free(header->design); free(header->date); free(header->part); free(header->time); free(header->version); return PYNQ_SUCCESS; } /** * Checks that the PS/PL is a 7-Series Zynq, or else the register info for the clock is entirely wrong. To support * other technologies, such as the ultrascale it is simply a case of modifying the defines and clock functions as appropriate */ static int checkMachineType() { struct utsname uname_info; if (uname(&uname_info) == -1) { fprintf(stderr, "Can not gather uname information to ensure that the PS/PL is a 7-Series Zynq\n"); return PYNQ_ERROR; } if (strcmp(ZYNQ_SERIES_7_IDENTIFIER, uname_info.machine) != 0) { fprintf(stderr, "For clock work the PS/PL must be a 7-Series Zynq, whereas uname returned '%s'\n", uname_info.machine); return PYNQ_ERROR; } return PYNQ_SUCCESS; } /** * Retreives the source clock MHZ frequency (without any divisors) from the appropriate registers */ static int getSrcClkMHZ(PYNQ_REGISTER* reg, size_t offset, float * src_clk_mhz) { unsigned int src_clk_idx; if (!PYNQ_readRegisterRange(reg, offset, 4, 5, &src_clk_idx)) return PYNQ_ERROR; unsigned int pll_reg=src_clk_idx < 2 ? 0x108 : src_clk_idx == 2 ? 0x100 : 0x104; unsigned int pll_fbdiv; if (!PYNQ_readRegisterRange(reg, pll_reg, 12, 18, &pll_fbdiv)) return PYNQ_ERROR; *src_clk_mhz=(DEFAULT_SRC_CLK_MHZ * pll_fbdiv); return PYNQ_SUCCESS; } /** * Will enable the UIO interface, ready to then capture interrupts raised on this */ static int enable_uio(PYNQ_UIO * state) { if (!state->active) { state->active=1; FILE * f = fopen(state->filename, "r+b"); if (f == NULL) { fprintf(stderr, "Error opening UIO file '%s'\n", state->filename); return PYNQ_ERROR; } char data[4]={0x00, 0x00, 0x00, 0x01}; size_t num_written=fwrite(&data, sizeof(char), 4, f); if (num_written != 4) { fprintf(stderr, "Expected to write 32 bit value to enable interrupt at '%s', but only wrote %d bytes\n", state->filename, num_written); return PYNQ_ERROR; } fclose(f); } return PYNQ_SUCCESS; } /** * Will pull down raised IRQs from the AXI interrupt controller, insert these into the state * and then acknowledge these on the AXI interrupt controller */ static void pullRaisedIRQs(PYNQ_AXI_INTERRUPT_CONTROLLER * state) { unsigned int raised_irqs, work, current_irq=0; // Read the interrupts PYNQ_readMMIO(&(state->mmio_window), &raised_irqs, 0x04, sizeof(unsigned int)); work=raised_irqs; while (work != 0) { if (work % 2 == 1) { unsigned int disable_irq=1 << current_irq; PYNQ_writeMMIO(&(state->mmio_window), &disable_irq, 0x14, sizeof(unsigned int)); appendOrInsertRaisedInterrupt(state, current_irq); } work = work >> 1; current_irq++; } // Acknowledge the interrupts PYNQ_writeMMIO(&(state->mmio_window), &raised_irqs, 0x0C, sizeof(unsigned int)); } /** * Will append the raising of an interrupt based on its IRQ to the state (by incrementing the counter) or if no such * state exists for this specific IRQ then that will be allocated and is stored single linked list fashion */ static void appendOrInsertRaisedInterrupt(PYNQ_AXI_INTERRUPT_CONTROLLER * state, int irq) { struct raised_interrupt_struct * interrupt = findRaisedInterruptStructure(state, irq); if (interrupt == NULL) { interrupt=(struct raised_interrupt_struct *) malloc(sizeof(struct raised_interrupt_struct)); interrupt->irq=irq; interrupt->number=0; interrupt->next=state->raised_interrupt_head; state->raised_interrupt_head=interrupt; } interrupt->active_waiting=0; interrupt->number++; } /** * Retrieves the interrupt information associated with a single interrupt by its IRQ for this controller, or NULL * if no information currently exists */ static struct raised_interrupt_struct * findRaisedInterruptStructure(PYNQ_AXI_INTERRUPT_CONTROLLER * state, int irq) { struct raised_interrupt_struct * head=state->raised_interrupt_head; while (head != NULL) { if (head->irq == irq) return head; head=head->next; } return NULL; } /** * Given the device name will search the proc filesystem to find the appropriate UIO path that corresponds to this, * which can then be used to directly read for UIO work */ static char * get_device_path(char * dev_name) { char full_name[512], line[512]; DIR *dp; struct dirent *ep; dp=opendir(UIO_DESCRIPTION_PATH); if (dp != NULL) { while (ep = readdir(dp)) { if (ep->d_type == DT_DIR || ep->d_type == DT_LNK) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; sprintf(full_name, "%s/%s/name", UIO_DESCRIPTION_PATH, ep->d_name); FILE * f = fopen(full_name, "r"); if (f != NULL) { if (fgets(line, sizeof(line), f)) { char * new_line=strrchr(line,'\n'); if (new_line != NULL) new_line[0]='\0'; if (strcmp(line, dev_name) == 0) { fclose(f); char * device_path=(char*) malloc(strlen(ep->d_name)+6); sprintf(device_path, "%s/%s", UIO_PATH, ep->d_name); return device_path; } } fclose(f); } } } } fprintf(stderr, "Can not find UIO location with corresponding name of '%s'", dev_name); return NULL; } /** * Given an IRQ number (at the Zynq PS) will look through the interrupts file in proc to locate the * corresponding dev name associated with this IRQ. Null is returned if no IRQ is located */ static char * get_uio_irq_devname(int irq) { char line[256], irq_str[20]; sprintf(irq_str, "%d", irq); FILE * f = fopen(INTERRUPTS_FILE, "r"); if (f == NULL) { fprintf(stderr, "Can not open '%s'\n", INTERRUPTS_FILE); return NULL; } while (fgets(line, sizeof(line), f)) { char * tokenised = strtok(line, " "); int c=0; char back_strings[256][3]; while (tokenised != NULL) { if (c > 2) strcpy(back_strings[0], back_strings[1]); if (c > 1) strcpy(back_strings[1], back_strings[2]); strcpy(back_strings[2], tokenised); tokenised = strtok(NULL, " "); c+=1; } if (c > 3 && strcmp(irq_str, back_strings[0]) == 0) { char * new_line=strrchr(back_strings[2],'\n'); if (new_line != NULL) new_line[0]='\0'; char * dev_name=(char*) malloc(strlen(back_strings[2]) + 1); strcpy(dev_name, back_strings[2]); fclose(f); return dev_name; } } fclose(f); fprintf(stderr, "Can not locate IRQ %d in interrupts file '%s'\n", irq, INTERRUPTS_FILE); return NULL; } /** * Issues a DMA transfer on the AXI DMA block to or from the shared memory at a specific offset with length and the * direction (write or read). Will error if the engine is not running or another transfer is in progress (but there are * two channels, one for write and one for read.) */ static int issueDMATransfer(PYNQ_AXI_DMA * state, PYNQ_SHARED_MEMORY * sm_state, size_t data_offset, size_t length, AXI_DMA_DIRECTION direction) { int mmio_offset = direction == AXI_DMA_WRITE ? state->write_channel_offset : state->read_channel_offset; unsigned int physical_address=((unsigned int) sm_state->physical_address) + (unsigned int) data_offset; unsigned int xfer_length=(unsigned int) length; if (!isDMAChannelRunning(state, direction)) { fprintf(stderr, "Error writing to DMA as engine is not running\n"); return PYNQ_ERROR; } if (!state->first_transfer[direction] && !isDMAChannelIdle(state, direction)) { fprintf(stderr, "Error writing to DMA as another transfer is in progress\n"); return PYNQ_ERROR; } PYNQ_writeMMIO(&(state->mmio_window), &physical_address, mmio_offset+0x18, sizeof(unsigned int)); PYNQ_writeMMIO(&(state->mmio_window), &xfer_length, mmio_offset+0x28, sizeof(unsigned int)); state->first_transfer[direction]=0; return PYNQ_SUCCESS; } /** * Starts a DMA channel in the write or read direction, either with or without interrupt raising enabled * as configured in the state */ static int startDMAChannel(PYNQ_AXI_DMA * state, AXI_DMA_DIRECTION direction) { int offset = direction == AXI_DMA_WRITE ? state->write_channel_offset : state->read_channel_offset; unsigned int command= state->interrupt_mode == 0 ? 0x0001 : 0x1001; return PYNQ_writeMMIO(&(state->mmio_window), &command, offset, sizeof(unsigned int)); } /** * Stops a DMA channel in a specific direction */ static int stopDMAChannel(PYNQ_AXI_DMA * state, AXI_DMA_DIRECTION direction) { int offset = direction == AXI_DMA_WRITE ? state->write_channel_offset : state->read_channel_offset; unsigned int command= 0x0000; return PYNQ_writeMMIO(&(state->mmio_window), &command, offset, sizeof(unsigned int)); } /** * Returns whether a DMA channel is running (i.e. started, but it can be running and idle) or not */ static int isDMAChannelRunning(PYNQ_AXI_DMA * state, AXI_DMA_DIRECTION direction) { int offset = direction == AXI_DMA_WRITE ? state->write_channel_offset : state->read_channel_offset; unsigned int read_byte; PYNQ_readMMIO(&(state->mmio_window), &read_byte, offset+4, sizeof(unsigned int)); return (read_byte & 0x01) == 0x00; } /** * Returns whether a DMA channel is running and idle (i.e. no DMA transfer is currently in progress.) */ static int isDMAChannelIdle(PYNQ_AXI_DMA * state, AXI_DMA_DIRECTION direction) { int offset = direction == AXI_DMA_WRITE ? state->write_channel_offset : state->read_channel_offset; unsigned int read_byte; PYNQ_readMMIO(&(state->mmio_window), &read_byte, offset+4, sizeof(unsigned int)); return (read_byte & 0x02) == 0x02; } /** * Given a full path filename this will return the filename alone, with the proceeding path stripped off */ static char * getBaseNameFromFile(char * filename) { char * slash_loc=strrchr(filename, '/'); if (slash_loc == NULL) return filename; return slash_loc+1; } /** * Given the filename of a bit stream will return the corresponding binary filename (this is quite simple, * but required for launching the bitstream payload on the PL.) */ static char * getBinNameFromBit(char * filename) { char * dot_point=strrchr(filename, '.'); char * bin_name=(char*) malloc((dot_point-filename)+5); memcpy(bin_name, filename, dot_point-filename); bin_name[dot_point-filename]='\0'; sprintf(bin_name, "%s.bin", bin_name); return bin_name; } /** * Given the filename and path of a bitstream this will extract the payload data (returned) and the length in * bytes (returned via the data_len argument). It completely ignores the header information and skips passed it. * Note that the bitstream is in big endian whereas the Zynq works in little endian, hence we need to do byte swaps * on the bitstream contents, both to find the payload part and also on the payload data itself (in 32 bit chunks) */ static char * extractBitstreamPayload(char * filename, int * data_len) { char * data_buffer=NULL; char * rawBitData=readRawBitfile(filename); short length; int payload_length; memcpy(&length, rawBitData, sizeof(short)); length=__bswap_16(length); // Strip the (2+n)-byte first field (2-bit length, n-bit data) and a two-byte unknown field (usually 1) size_t offset=4+length; while (1==1) { char desc=rawBitData[offset]; offset++; if (desc == 0x65) { memcpy(&(payload_length), &rawBitData[offset], sizeof(int)); payload_length=__bswap_32(payload_length); *data_len=payload_length; offset+=4; data_buffer=(char*) malloc(payload_length); memcpy(data_buffer, &rawBitData[offset], payload_length); // Now iterate through and swap from big endian to little endian for (int i=0;i<payload_length/4;i++) { int data_item; memcpy(&data_item, &(data_buffer[i*4]), sizeof(int)); data_item=__bswap_32(data_item); memcpy(&(data_buffer[i*4]), &data_item, sizeof(int)); } if (payload_length%4 != 0) { // Handle last element if not divisible by four int remainder_size=payload_length - ((payload_length/4) * 4); int data_item=0; memcpy(&data_item, &(data_buffer[(payload_length/4) * 4]), remainder_size); data_item=__bswap_32(data_item); memcpy(&(data_buffer[(payload_length/4) * 4]), &data_item, sizeof(int)); } break; } else { memcpy(&length, &rawBitData[offset], sizeof(short)); length=__bswap_16(length); offset+=2+length; } } return data_buffer; } /** * Given the filename and path of a bitstream this will extract the full header and payload data and return this * via the header argument. * Note that the bitstream is in big endian whereas the Zynq works in little endian, hence we need to do byte swaps * on the bitstream contents, both to find the payload part and also on the payload data itself (in 32 bit chunks) */ static void extractBitstreamInfo(char * filename, PYNQ_BITSTREAM_INFO * header) { char * data_buffer=NULL; char * rawBitData=readRawBitfile(filename); short length; memcpy(&length, rawBitData, sizeof(short)); length=__bswap_16(length); // Strip the (2+n)-byte first field (2-bit length, n-bit data) and a two-byte unknown field (usually 1) size_t offset=4+length; while (1==1) { char desc=rawBitData[offset]; offset++; if (desc != 0x65) { memcpy(&length, &rawBitData[offset], sizeof(short)); length=__bswap_16(length); offset+=2; data_buffer=(char*) malloc(length+1); memcpy(data_buffer, &rawBitData[offset], length); offset+=length; if (desc == 0x61) { data_buffer[length]='\0'; char * semi_point=strrchr(data_buffer, ';'); size_t str_len=semi_point-data_buffer; header->design=(char*) malloc(str_len+1); memcpy(header->design, data_buffer, str_len); header->design[str_len]='\0'; str_len=strlen(data_buffer)-str_len; header->version=(char*) malloc(str_len+1); memcpy(header->version, &semi_point[1], str_len); header->version[str_len]='\0'; } else if (desc == 0x62) { header->part=(char*) malloc(length+1); memcpy(header->part, data_buffer, length); header->part[length]='\0'; } else if (desc == 0x63) { header->date=(char*) malloc(length+1); memcpy(header->date, data_buffer, length); header->date[length]='\0'; } else if (desc == 0x64) { header->time=(char*) malloc(length+1); memcpy(header->time, data_buffer, length); header->time[length]='\0'; } free(data_buffer); } if (desc == 0x65) { memcpy(&(header->data_length), &rawBitData[offset], sizeof(int)); header->data_length=__bswap_32(header->data_length); offset+=4; header->data=(char*) malloc(header->data_length); memcpy(header->data, &rawBitData[offset], header->data_length); // Now iterate through and swap from big endian to little endian for (int i=0;i<header->data_length/4;i++) { int data_item; memcpy(&data_item, &(header->data[i*4]), sizeof(int)); data_item=__bswap_32(data_item); memcpy(&(header->data[i*4]), &data_item, sizeof(int)); } if (header->data_length%4 != 0) { // Handle last element if not divisible by four int remainder_size=header->data_length - ((header->data_length/4) * 4); int data_item=0; memcpy(&data_item, &(header->data[(header->data_length/4) * 4]), remainder_size); data_item=__bswap_32(data_item); memcpy(&(header->data[(header->data_length/4) * 4]), &data_item, sizeof(int)); } break; } } free(rawBitData); } /** * Given the filename and path of the bitstream file this will read the byte contents of that file and return it. * We don't know how large the file contents are, so it reads the information in chunks and then resizes a * buffer to store this into piece by piece. */ static char * readRawBitfile(char * filename) { FILE * f = fopen(filename, "rb"); char * buffer = (char *) malloc(READ_CHUNK_SIZE); char * data_byte_buffer = NULL; size_t data_byte_buffer_size=0; size_t read_bytes=READ_CHUNK_SIZE; while (read_bytes == READ_CHUNK_SIZE) { read_bytes=fread(buffer, sizeof(char), READ_CHUNK_SIZE, f); data_byte_buffer=realloc(data_byte_buffer, data_byte_buffer_size+read_bytes); memcpy(&data_byte_buffer[data_byte_buffer_size], buffer, read_bytes); data_byte_buffer_size+=read_bytes; } fclose(f); free(buffer); return data_byte_buffer; }
keshavgupta21/pynq_api_cpp
src/pynq_api.h
<filename>src/pynq_api.h /* * BSD 3-Clause License * * Copyright (c) 2019, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PYNQ_API_H_INCLUDED #define PYNQ_API_H_INCLUDED #include <stdlib.h> #define PYNQ_SUCCESS 1 #define PYNQ_ERROR 0 typedef struct mmio_state_struct { char * buffer; int file_handle; unsigned int length, address_base, virt_base, virt_offset; } PYNQ_MMIO_WINDOW; typedef enum gpio_direction_emum { GPIO_OUT=0, GPIO_IN=1 } GPIO_DIRECTION; typedef struct gpio_state_struct { int index; GPIO_DIRECTION direction; char * filename; } PYNQ_GPIO; typedef struct bit_file_header_struct { char *design, *version, *part, *date, *time; int data_length; char * data; } PYNQ_BITSTREAM_INFO; typedef struct shared_memory_state_struct { void * pointer; unsigned long physical_address; } PYNQ_SHARED_MEMORY; typedef enum axi_dma_direction_enum { AXI_DMA_WRITE=0, AXI_DMA_READ=1 } AXI_DMA_DIRECTION; typedef struct axi_dma_transfer_struct { PYNQ_MMIO_WINDOW mmio_window; unsigned int write_channel_offset, read_channel_offset; unsigned char first_transfer[2]; int interrupt_mode; } PYNQ_AXI_DMA; typedef struct uio_struct { char * filename; unsigned char active; int irq; } PYNQ_UIO; struct raised_interrupt_struct { int irq, number; unsigned char active_waiting; struct raised_interrupt_struct * next; }; typedef struct interrupt_controller_struct { PYNQ_MMIO_WINDOW mmio_window; struct raised_interrupt_struct * raised_interrupt_head; unsigned int enabled_hw_interrupts; } PYNQ_AXI_INTERRUPT_CONTROLLER; typedef struct register_struct { PYNQ_MMIO_WINDOW mmio_window; } PYNQ_REGISTER; typedef struct hls_struct { PYNQ_MMIO_WINDOW mmio_window; } PYNQ_HLS; #ifdef __cplusplus extern "C" { #endif // Core API unsigned long long PYNQ_Wtime(); int PYNQ_getCPUClockFreq(float* frequency); int PYNQ_getPLClockFreq(unsigned int clock_index, float* frequency); int PYNQ_setPLClockFreq(unsigned int clock_index, float * freq, int * div0, int *div1); int PYNQ_openRegister(PYNQ_REGISTER* reg_state, size_t address, size_t width); int PYNQ_readRegister(PYNQ_REGISTER* reg_state, size_t address, int index, unsigned int* data); int PYNQ_readRegisterRange(PYNQ_REGISTER* reg_state, size_t address, int start_index, int end_index, unsigned int* data); int PYNQ_setRegister(PYNQ_REGISTER* reg_state, size_t address, int index, unsigned int* data); int PYNQ_setRegisterRange(PYNQ_REGISTER* reg_state, size_t address, int start_index, int end_index, unsigned int* data); int PYNQ_closeRegister(PYNQ_REGISTER* reg_state); int PYNQ_openUIO(PYNQ_UIO* uio_state, int irq); int PYNQ_closeUIO(PYNQ_UIO* uio_state); int PYNQ_waitForUIO(PYNQ_UIO* uio_state, int* flag); int PYNQ_checkForUIO(PYNQ_UIO* uio_state, int* flag); int PYNQ_allocatedSharedMemory(PYNQ_SHARED_MEMORY* sm_state, size_t length, int allow_reset); int PYNQ_freeSharedMemory(PYNQ_SHARED_MEMORY* sm_state); int PYNQ_createMMIOWindow(PYNQ_MMIO_WINDOW* mmio_state, size_t address, size_t length); int PYNQ_closeMMIOWindow(PYNQ_MMIO_WINDOW* mmio_state); int PYNQ_writeMMIO(PYNQ_MMIO_WINDOW* mmio_state, void* data, size_t offset, size_t length); int PYNQ_readMMIO(PYNQ_MMIO_WINDOW* mmio_state, void* data, size_t offset, size_t length); int PYNQ_openGPIO(PYNQ_GPIO* gpio_state, int index, GPIO_DIRECTION direction); int PYNQ_closeGPIO(PYNQ_GPIO* gpio_state); int PYNQ_writeGPIO(PYNQ_GPIO* gpio_state, int* data); int PYNQ_readGPIO(PYNQ_GPIO* gpio_state, int* data); int PYNQ_loadBitstream(char* filename); int PYNQ_extractBitstreamInfo(PYNQ_BITSTREAM_INFO* info, char* filename); int PYNQ_freeBitstreamInfo(PYNQ_BITSTREAM_INFO* info); // HLS API int PYNQ_openHLS(PYNQ_HLS* hls_state, size_t address, size_t width); int PYNQ_startHLS(PYNQ_HLS* hls_state); int PYNQ_testHLSCompleted(PYNQ_HLS* hls_state, int* flag); int PYNQ_waitForHLS(PYNQ_HLS* hls_state); int PYNQ_writeToHLS(PYNQ_HLS* hls_state, void* data, size_t offset, size_t length); int PYNQ_readFromHLS(PYNQ_HLS* hls_state, void* data, size_t offset, size_t length); int PYNQ_closeHLS(PYNQ_HLS* hls_state); // AXI DMA API int PYNQ_openDMA(PYNQ_AXI_DMA* dma_state, size_t base_address); int PYNQ_setDMATransferInterruptMode(PYNQ_AXI_DMA* dma_state, int interrupt_mode); int PYNQ_issueDMATransfer(PYNQ_AXI_DMA* dma_state, PYNQ_SHARED_MEMORY* shared_memory, size_t offset, size_t length, AXI_DMA_DIRECTION direction); int PYNQ_writeDMA(PYNQ_AXI_DMA* dma_state, PYNQ_SHARED_MEMORY* shared_memory, size_t offset, size_t length); int PYNQ_readDMA(PYNQ_AXI_DMA* dma_state, PYNQ_SHARED_MEMORY* shared_memory, size_t offset, size_t length); int PYNQ_testForDMAComplete(PYNQ_AXI_DMA* dma_state, AXI_DMA_DIRECTION direction, int* flag); int PYNQ_waitForDMAComplete(PYNQ_AXI_DMA* dma_state, AXI_DMA_DIRECTION direction); int PYNQ_closeDMA(PYNQ_AXI_DMA* dma_state); // AXI Interrupt controller int PYNQ_openInterruptController(PYNQ_AXI_INTERRUPT_CONTROLLER* interrupt_ctrl_state, size_t base_address); int PYNQ_registerInterrupt(PYNQ_AXI_INTERRUPT_CONTROLLER* interrupt_ctrl_state, int irq, int generate_hw_interrupt); int PYNQ_testForInterrupt(PYNQ_AXI_INTERRUPT_CONTROLLER* interrupt_ctrl_state, int irq, int* flag); int PYNQ_waitForInterrupt(PYNQ_AXI_INTERRUPT_CONTROLLER* interrupt_ctrl_state, int irq); int PYNQ_closeInterruptController(PYNQ_AXI_INTERRUPT_CONTROLLER* interrupt_ctrl_state); // AXI GPIO additions // author: <NAME> <<EMAIL>> #define PYNQ_AXI_GPIO_CH1DATA_OFFSET 0x0 #define PYNQ_AXI_GPIO_CH1DATA_LEN 0x4 #define PYNQ_AXI_GPIO_CH1TRI_OFFSET 0x4 #define PYNQ_AXI_GPIO_CH1TRI_LEN 0x4 #define PYNQ_AXI_GPIO_CH2DATA_OFFSET 0x8 #define PYNQ_AXI_GPIO_CH2DATA_LEN 0x4 #define PYNQ_AXI_GPIO_CH2TRI_OFFSET 0xc #define PYNQ_AXI_GPIO_CH2TRI_LEN 0x4 typedef struct axi_gpio_ch_struct { PYNQ_MMIO_WINDOW mmio_window; size_t dataOffset; size_t dataLen; size_t triOffset; size_t triLen; } PYNQ_AXI_GPIO_CH; // AXI GPIO API int PYNQ_openAXIGPIOCH(PYNQ_AXI_GPIO_CH* gpio_ch, size_t base_address, size_t chnum); int PYNQ_writeAXIGPIOCH(PYNQ_AXI_GPIO_CH* gpio_ch, unsigned int *data); int PYNQ_readAXIGPIOCH(PYNQ_AXI_GPIO_CH* gpio_ch, unsigned int *data); int PYNQ_closeAXIGPIOCH(PYNQ_AXI_GPIO_CH* gpio_ch); #ifdef __cplusplus } #endif #endif // PYNQ_API_H_INCLUDED
keshavgupta21/pynq_api_cpp
src/pynq_axi_gpio.c
<reponame>keshavgupta21/pynq_api_cpp #include "pynq_api.h" int PYNQ_openAXIGPIOCH(PYNQ_AXI_GPIO_CH* gpio_ch, size_t base_address, size_t chnum) { PYNQ_createMMIOWindow(&(gpio_ch->mmio_window), base_address, 0x10); if (chnum == 1) { gpio_ch->dataOffset = PYNQ_AXI_GPIO_CH1DATA_OFFSET; gpio_ch->dataLen = PYNQ_AXI_GPIO_CH1DATA_LEN; gpio_ch->triOffset = PYNQ_AXI_GPIO_CH1TRI_OFFSET; gpio_ch->triLen = PYNQ_AXI_GPIO_CH1TRI_LEN; return PYNQ_SUCCESS; } else if (chnum == 2) { gpio_ch->dataOffset = PYNQ_AXI_GPIO_CH2DATA_OFFSET; gpio_ch->dataLen = PYNQ_AXI_GPIO_CH2DATA_LEN; gpio_ch->triOffset = PYNQ_AXI_GPIO_CH2TRI_OFFSET; gpio_ch->triLen = PYNQ_AXI_GPIO_CH2TRI_LEN; return PYNQ_SUCCESS; } else { return PYNQ_ERROR; } } int PYNQ_writeAXIGPIOCH(PYNQ_AXI_GPIO_CH* gpio_ch, unsigned int *data) { return PYNQ_writeMMIO(&(gpio_ch->mmio_window), data, gpio_ch->dataOffset, gpio_ch->dataLen); } int PYNQ_readAXIGPIOCH(PYNQ_AXI_GPIO_CH* gpio_ch, unsigned int *data) { return PYNQ_readMMIO(&(gpio_ch->mmio_window), data, gpio_ch->dataOffset, gpio_ch->dataLen); } int PYNQ_closeAXIGPIOCH(PYNQ_AXI_GPIO_CH* gpio_ch) { return PYNQ_closeMMIOWindow(&(gpio_ch->mmio_window)); }
SunHaiMeng/SHMMapBDMethod
SHMMapMethod/SHMMapMethod/SHMMapTools.h
// // SHMMapTools.h // SHMMapMethod // // Created by apple on 2018/11/29. // Copyright © 2018年 GXT. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface SHMMapTools : NSObject @end NS_ASSUME_NONNULL_END
SunHaiMeng/SHMMapBDMethod
SHMMapMethod/SHMMapMethod/SHMLocationMap.h
// // SHMLocationMap.h // MinSu // // Created by apple on 2018/8/21. // Copyright © 2018年 GXT. All rights reserved. // #import <Foundation/Foundation.h> //#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件 //#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件 //#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件 //#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件 //#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件 //#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入计算工具所有的头文件 //#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周边雷达功能所有的头文件 //#import <CoreLocation/CLLocation.h> //#import <CoreLocation/CLLocationManager.h> @interface SHMLocationMap : NSObject //+(instancetype)defaultManager; //-(void)startUploadLocation:(void(^)(bool))callback; //-(void)stopUploadLocation; //-(void)getLocation:(void(^)(double,double,NSError *))callback; ////手动上传坐标 //-(void)locationRequstLocation:(double)latitude longitude:(double)longitude; ////计算坐标距离 //-(float)getDistanceBetweenTwoPont:(CLLocationCoordinate2D)fristCoor secondCoor:(CLLocationCoordinate2D)secondCoor; //@property (readonly,nonatomic) BOOL isUploadingLocation; @end
avahidi/bmlib
src/div10.c
<gh_stars>1-10 #include "bmlib.h" #ifdef BMLIB_HAS_DIV10 /* divide by ten 10, from Hacker's Delight chapter 10 */ uint32_t divu10(uint32_t n) { uint32_t q, r; q = (n >> 1) + (n >> 2); q = q + (q >> 4); q = q + (q >> 8); q = q + (q >> 16); q = q >> 3; r = n - q*10; return q + ((r + 6) >> 4); } #endif /* BMLIB_HAS_DIV10 */
avahidi/bmlib
test/src/main.c
#include "bmlib.h" #include "testing.h" extern void test_div(); extern void test_string(); extern void test_string_strtok(); extern void test_string_mem(); extern void test_stdio(); int main(int argc, char **argv) { test_start(); test_div(); test_string(); test_string_strtok(); test_string_mem(); test_stdio(); test_end(); }
avahidi/bmlib
test/src/testing.h
/* * minimal testing framework */ #ifndef __TESTING_H__ #define __TESTING_H__ #include <stdbool.h> #define test(msg, v) \ test_record0(msg, v, "") #define test_eq(msg, a, b) \ test_record2(msg, (a) == (b), "%d == %d", (int) a, (int) b) #define test_neq(msg, a, b) \ test_record2(msg, (a) != (b), "%d != %d", (int) a, (int) b) /* helpers */ #define test_record0(msg, v, op) \ test_record0_(msg, v, op, __LINE__, __FILE__) #define test_record1(msg, v, a, op) \ test_record1_(msg, v, op, a, __LINE__, __FILE__) #define test_record2(msg, v, op, a, b) \ test_record2_(msg, v, op, a, b, __LINE__, __FILE__) #define test_record3(msg, v, op, a, b, c) \ test_record3_(msg, v, op, a, b, c, __LINE__, __FILE__) /* backend functions */ extern void test_record0_(char *msg, bool v, const char *op, int lineno, const char *file); extern void test_record1_(char *msg, bool v, const char *op, int a, int lineno, const char *file); extern void test_record2_(char *msg, bool v, const char *op, int a, int b, int lineno, const char *file); extern void test_record3_(char *msg, bool v, const char *op, int a, int b, int c, int lineno, const char *file); /* admin functions */ void test_start(); void test_end(); void test_group_start(const char *name); void test_group_end(); /* the rest */ void fatal(const char *msg); #endif /* __TESTING_H__ */
avahidi/bmlib
test/src/stdio.c
<gh_stars>1-10 #include "bmlib.h" #include "testing.h" void test_stdio() { char buffer[100]; int n; test_group_start("stdio"); /* snprintf */ n = snprintf(buffer, 100, "AB%d%c%s%x", 23, 'c', "xyz", 0x123); test_eq("snprintf A", 0, strcmp(buffer, "AB23cxyz00000123")); test_eq("snprintf A2", n, strlen(buffer) + 1); n = snprintf(buffer, 4, "%s", "ABCDEF"); test_eq("snprintf B", 0, strcmp(buffer, "ABC")); test_eq("snprintf B2", n, 4); snprintf(buffer, 5, "%x", 666); test_eq("snprintf C", 0, strcmp(buffer, "0000")); snprintf(buffer, 100, "%x %X %p %P", 0x123, 0x234, 0x345, 0x456); test_eq("snprintf D", 0, strcmp(buffer, "00000123 0000000000000234 0x00000345 0x0000000000000456")); test_group_end(); }
avahidi/bmlib
test/src/string.c
#include "bmlib.h" #include "testing.h" void test_string() { char buffer[10]; char *tmp; test_group_start("string"); /* strlen */ test_eq("strlen test A", 4, strlen("ABCD")); test_eq("strlen test B", 0, strlen("")); /* strchr */ tmp = "ABC"; test_eq("strchr test A", tmp + 2, strchr(tmp, 'C')); test_eq("strchr test B", 0, strchr(tmp, 'D')); tmp = "ABCC"; test_eq("strchr test B", tmp + 2, strchr(tmp, 'C')); tmp = "\0BCD"; test_eq("strchr test D", 0, strchr(tmp, 'D')); /* strcmp */ test_eq("strcmp test A", 0, strcmp("ABCD", "ABCD")); test_eq("strcmp test B", 0, strcmp("", "")); test_neq("strcmp test C", 0, strcmp("ABC", "ABZ")); test_eq("strcmp test D", 'A', strcmp("A", "")); test_eq("strcmp test E", -'A', strcmp("", "A")); /* strncmp */ test_eq("strncmp test A", 0, strncmp("ABCD", "ABCD", 4)); test_eq("strncmp test A", 0, strncmp("ABCx", "ABCy", 3)); test_eq("strncmp test A", 0, strncmp("foo", "bar", 0)); /* strcpy */ strcpy(buffer, "ABCD"); test_eq("strcpy test A", 0, strcmp(buffer, "ABCD")); strcpy(buffer, ""); test_eq("strcpy test B", 0, strcmp(buffer, "")); /* strncpy */ strcpy(buffer, "xxx?"); /* 4 = ?, 5 = '\0' */ strncpy(buffer, "ABCD", 3); test_eq("strn test A", 0, strcmp(buffer, "ABC?")); strncpy(buffer, "", 1); test_eq("strncpy test B", 0, strlen(buffer)); buffer[4] = buffer[5] = buffer[6] = buffer[7] = '!'; strncpy(buffer, "ABCD", 8); test_eq("strncpy test C1", 0, strcmp(buffer, "ABCD")); test_eq("strncpy test C2", 0, buffer[4] | buffer[5] | buffer[6] | buffer[7]); test_group_end(); }
avahidi/bmlib
test/src/string_mem.c
#include "bmlib.h" #include "testing.h" void test_string_mem() { char buffer1[10], buffer2[10]; char *tmp; int i; test_group_start("string_mem"); /* memset */ for(i = 0; i < 10; i++) buffer1[i] = 0x33; memset((void *)buffer1, 0x44, 9); for(i = 0; i < 9; i++) test_eq("memset test A1", 0x44, buffer1[i]); test_eq("memset test A2", 0x33, buffer1[9]); memset((void *)buffer1, -1, 8); for(i = 0; i < 8; i++) test_eq("memset test B1", -1, buffer1[i]); test_eq("memset test B2", 0x44, buffer1[8]); test_eq("memset test B3", 0x33, buffer1[9]); /* memcpy */ memset(buffer2, 0x11, 10); strcpy(buffer1, "ABC"); memcpy(buffer2, buffer1, 4); /* buffer2 = A B C \'0 0x11 0x11 ... */ test_eq("memset A1", 0, strcmp(buffer2, "ABC")); for(i = 4; i < 10; i++) test_eq("memset A2", 0x11, buffer2[i]); test_group_end(); }
avahidi/bmlib
src/string.c
<filename>src/string.c<gh_stars>1-10 #include <bmlib.h> #ifdef BMLIB_HAS_STRING /* * string functions. * some are optimised for size not efficiency or libc conforming! */ int strlen(const char *s) { int ret = 0; while(*s++ != '\0') ret++; return ret; } void strcpy(char *dst, const char *src) { for(; *src != '\0'; ) *dst++ = *src++; *dst = '\0'; } void strncpy(char *dst, const char *src, int n) { char *tmp = dst; for(; n > 0 && *src != '\0'; n--) *dst++ = *src++; while(n-- > 0) *dst++ = '\0'; } char *strchr(const char *s, char c) { do { if(*s == c) return (char *)s; } while(*s++ != '\0'); return 0; } int strcmp(const char *s1, const char *s2) { while(*s1 == *s2 && *s1 != '\0') { s1++; s2++; } return (int)(*s1) - (int)(*s2); } int strncmp(const char *s1, const char *s2, int n) { int diff; while(n--) { diff = (int)(*s1) - (int)(*s2); if(diff || *s1 == '\0') return diff; s1++; s2++; } return 0; } #endif /* BMLIB_HAS_STRING */ #ifdef BMLIB_HAS_STRING_MEM void memcpy(void *dst, const void *src, int n) { char *out = (char *)dst; const char *in = (const char *)src; while(n-- > 0) { *out++ = *in++; } } void memset(void *dst, int c, int n) { char *out = (char *)dst; while(n-- > 0) { *out++ = c; } } #endif /* BMLIB_HAS_STRING_MEM */ #ifdef BMLIB_HAS_STRING_STRTOK char *strtok(char *str, const char *delim) { static char *save; return strtok_r(str, delim, &save); } char *strtok_r(char *str, const char *delim, char **save) { char *e; if(!str) { str = *save; if(!str) return str; } /* delim before */ for(; *str != '\0' && strchr(delim, *str); str++) ; if( *str == '\0') return 0; /* end of text */ for(e = str; *e != '\0' && !strchr(delim, *e); e++) ; if( *e != '\0') *e++ = '\0'; *save = e; return str; } #endif /* BMLIB_HAS_STRING_STRTOK */
avahidi/bmlib
test/src/div.c
<filename>test/src/div.c #include "bmlib.h" #include "testing.h" void test_div() { test_group_start("div"); test_eq("div A", 5, divu10(55)); test_group_end(); }
avahidi/bmlib
src/config/bmconfig.h
#ifndef __BMCONFIG_H__ #define __BMCONFIG_H__ /* * This is the library configuration file, which defines what parts are included. * Comment definitions to disable specific parts. * * Note that you can provide a different bmconfig.h file by setting the CONFIG make variable. */ #define BMLIB_HAS_PRINTF_X64 /* %X prints 64-bit hex */ #define BMLIB_HAS_PRINTF /* printf, sprintf */ #define BMLIB_HAS_STRING /* strlen, strcpy etc */ #define BMLIB_HAS_STRING_MEM /* memset + memcpy */ #define BMLIB_HAS_STRING_STRTOK /* strtok, strtok_r */ #define BMLIB_HAS_DIV10 /* divide by 10 to avoid */ #endif /* __BMCONFIG_H__ */
avahidi/bmlib
test/src/string_strtok.c
#include "bmlib.h" #include "testing.h" static void test_one(const char *str, const char *delim, const char **expected, int _r) { int i; char buffer[1024]; char *save, *token; strcpy(buffer, str); for(i = 0; expected[i]; i++) { if(_r) token = strtok_r( i == 0 ? buffer : 0, delim, &save); else token = strtok( i == 0 ? buffer : 0, delim); test("strtok/strtok_r", !strcmp(expected[i], token)); } /* check it is not returning more */ if(_r) token = strtok_r(0, delim, &save); else token = strtok(0, delim); test("strtok/strtok_r returning more tokens?", !token); } void test_string_strtok() { const char *delim = " ,\t"; const char *text1 = " abc 1234 , 5\t6"; const char *answer1[] = { "abc", "1234", "5", "6", 0 }; const char *text2 = " a "; const char *answer2[] = { "a", 0 }; const char *text3 = "b"; const char *answer3[] = { "b", 0 }; const char *empty[] = { 0 }; char *null = 0; test_group_start("string_strtok"); test_one(text1, delim, answer1, 0); test_one(text1, delim, answer1, 1); test_one(text2, delim, answer2, 0); test_one(text2, delim, answer2, 1); test_one(text3, delim, answer3, 0); test_one(text3, delim, answer3, 1); /* some edge cases */ test_one("", delim, empty, 0); test_one("", delim, empty, 1); test("NULL str & save -> NULL", !strtok_r(0, delim, &null)); test_group_end(); }
avahidi/bmlib
src/bmlib.h
<gh_stars>1-10 #ifndef __BMLIB_H__ #define __BMLIB_H__ #include "bmconfig.h" #ifdef __ASSEMBLER__ #else /* __ASSEMBLER__ */ #include <stdint.h> #include <stdarg.h> /* often used attributes */ #define __packed __attribute__((packed)) #define __naked __attribute__((naked)) #define __weak __attribute__((weak)) #ifdef BMLIB_HAS_PRINTF extern void printf(const char *fmt, ...); extern void vprintf(const char *fmt, va_list ap); extern int snprintf(char *buffer, int size, const char *fmt, ...); extern int putchar(int c); /* defined by YOU */ #endif #ifdef BMLIB_HAS_STRING extern int strlen(const char *s); extern void strcpy(char *dst, const char *src); extern void strncpy(char *dst, const char *src, int n); extern char *strchr(const char *s, char c); extern int strcmp(const char *s1, const char *s2); extern int strncmp(const char *s1, const char *s2, int n); #endif #ifdef BMLIB_HAS_STRING_MEM extern void memcpy(void *dst, const void *src, int n); extern void memset(void *dst, int c, int n); #endif #ifdef BMLIB_HAS_STRING_STRTOK extern char *strtok(char *str, const char *delim); extern char *strtok_r(char *str, const char *delim, char **save); #endif #ifdef BMLIB_HAS_DIV10 extern uint32_t divu10(uint32_t n); #endif #endif /* ! __ASSEMBLER__ */ #endif /* __BMLIB_H__ */
avahidi/bmlib
test/src/testing.c
/* * minimal testing framework */ #include <stdbool.h> #include "bmlib.h" #include "testing.h" /* instead of the whole <stdlib.h>: */ extern void exit(int); static bool inside_group = false; static int total_cnt = 0; static int total_fail = 0; static int group_cnt = 0; static int group_fail = 0; static int groups = 0; void fatal(const char *msg) { printf( "FATAL ERROR: %s\n", msg); exit(20); } void assert(const char *msg, bool b) { if(!b) fatal(msg); } /* * groups */ void test_group_start(const char *name) { printf(" GROUP '%s'...\n", name); assert("group not correctly ended", !inside_group); inside_group = true; groups++; group_fail = 0; group_cnt = 0; } void test_group_end() { assert("Test group end without start", inside_group); inside_group = false; total_cnt += group_cnt; total_fail += group_fail; if(group_fail) printf(" group failed with %d errors in %d tests\n", group_fail, group_cnt); } /* * all tests */ void test_start() { printf("TESTING started\n"); } void test_end() { printf("TESTING ended\n"); if(total_fail) { printf("FAILURE: %d tests of %d FAILED\n", total_fail, total_cnt); exit(20); } else { printf("SUCCESS: %d tests in %d groups PASSED\n", total_cnt, groups); } } /* * backend */ void test_record0_(char *msg, bool v, const char *op, int lineno, const char *file) { group_cnt++; if(!v) { group_fail++; printf(" FAILED: %s in %s:%d\n ", msg, file, lineno); printf(op); printf("\n"); } } void test_record1_(char *msg, bool v, const char *op, int a, int lineno, const char *file) { group_cnt++; if(!v) { group_fail++; printf(" FAILED: %s in %s:%d\n ", msg, file, lineno); printf(op, a); printf("\n"); } } void test_record2_(char *msg, bool v, const char *op, int a, int b, int lineno, const char *file) { group_cnt++; if(!v) { group_fail++; printf(" FAILED: %s in %s:%d\n ", msg, file, lineno); printf(op, a, b); printf("\n"); } } void test_record3_(char *msg, bool v, const char *op, int a, int b, int c, int lineno, const char *file) { group_cnt++; if(!v) { group_fail++; printf(" FAILED: %s in %s:%d\n ", msg, file, lineno); printf(op, a, b, c); printf("\n"); } }
avahidi/bmlib
src/stdio.c
<filename>src/stdio.c<gh_stars>1-10 #include "bmlib.h" #include <stdarg.h> #ifdef BMLIB_HAS_PRINTF /* write targets for *printf() */ struct write_context { void (*write)(struct write_context *, int data); char *buffer; int curr, max; }; static void sprintf_write(struct write_context *c, int data) { if(c->curr < c->max - 1) c->buffer[c->curr++] = data; } /* * endpoint for all printf() functions. * You need to supply you own putchar(), for example something * that writes to your UART or to your log buffer */ static void printf_write(struct write_context *c, int data) { putchar(data); if(data == '\n') putchar('\r'); } /* * MINIMAL printf implementation */ static void printf_string(struct write_context *ctx, char *str) { if(!str) str = "(null)"; while(*str) ctx->write(ctx, *str++); } static void printf_int(struct write_context *ctx, int i) { int tmp, f = 0, neg = 0; char buffer[25]; if(i < 0) { neg ++; i = - i; } do { #ifdef BMLIB_HAS_DIV10 tmp = i; i = divu10(i); buffer[f++] = '0' + (tmp - i * 10); #else buffer[f++] = '0' + (i % 10); i /= 10; #endif } while(i); if(neg) buffer[f++] = '-'; while(f) ctx->write(ctx, buffer[--f]); } static void printf_hex32(struct write_context *ctx, uint32_t n) { uint32_t h, i; for(i = 8; i; i--) { h = (n >> 28) & 15; n <<= 4; if(h < 10) h += '0'; else h += 'A' - 10; ctx->write(ctx, h); } } static void printf_hex64(struct write_context *ctx, uint64_t n) { printf_hex32( ctx, (uint32_t)(n >> 32)); printf_hex32( ctx, (uint32_t)n); } static void vcprintf(struct write_context *ctx, const char *fmt, va_list args) { int c; for(;;) { c = *fmt; if(c == '\0') return; fmt ++; if(c == '%') { c = *fmt++; switch(c) { case 's': printf_string(ctx, va_arg(args, char *)); break; case 'd': printf_int(ctx, va_arg(args, int)); break; case 'P': #ifdef BMLIB_HAS_PRINTF_X64 printf_string(ctx, "0x"); #endif /* falls through */ case 'X': #ifdef BMLIB_HAS_PRINTF_X64 /* X is 64-bit hex */ printf_hex64(ctx, va_arg(args, uint64_t)); break; #else /* falls through */ #endif case 'p': printf_string(ctx, "0x"); /* falls through */ case 'x': printf_hex32(ctx, va_arg(args, uint32_t)); break; case 'c': ctx->write(ctx, va_arg(args, int)); break; case '\0': case '%': ctx->write(ctx, c); break; default: ctx->write(ctx, '%'); ctx->write(ctx, c); } } else { ctx->write(ctx, c); } } } /* * printf variants */ void vprintf(const char *fmt, va_list ap) { struct write_context ctx; ctx.write = printf_write; vcprintf(&ctx, fmt, ap); } void printf(const char *fmt, ...) { va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); } int snprintf(char *buffer, int size, const char *fmt, ...) { va_list args; struct write_context ctx; va_start(args, fmt); ctx.write = sprintf_write; ctx.buffer = buffer; ctx.curr = 0; ctx.max = size; vcprintf(&ctx, fmt, args); buffer[ctx.curr] = '\0'; va_end(args); return ctx.curr + 1; } #endif /* BMLIB_HAS_PRINTF */
pengdao/simcc
simcc/json/json_object.h
// Created: 2009/08/07 // Author: weizili #pragma once #include "simcc/inner_pre.h" #include "json_common.h" #include "json_value.h" #include "json_parser.h" namespace simcc { namespace json { class JSONArray; class JSONTokener; class SIMCC_EXPORT JSONObject : public Object, public JSONParser { public: typedef std::map<string, ObjectPtr> ObjectPtrMap; typedef ObjectPtrMap Map; typedef ObjectPtrMap::iterator Iterator; typedef ObjectPtrMap::const_iterator ConstIterator; typedef Iterator iterator; typedef ConstIterator const_iterator; typedef ObjectPtrMap::reverse_iterator reverse_iterator; typedef ObjectPtrMap::const_reverse_iterator const_reverse_iterator; public: enum { Type = kJSONObject }; JSONObject() : Object(kJSONObject) {} // Construct a JSONObject from a source JSON text string. // @note Don't use this tow constructors, unless you can make sure // the json text string is valid format. You can use JSONObject() // instead, and use Parse(...) method to build a JSON object // from a json text string. // @param source A string beginning // with <code>{</code>&nbsp;<small>(left brace)</small> and ending // with <code>}</code>&nbsp;<small>(right brace)</small>. // @param source_len The length of the source string // if it Equals -1, we will use strlen(source) to calculate the length. JSONObject(const string& source); JSONObject(const char* source, const simcc::int32 source_len = -1); virtual ~JSONObject(); public: // Construct a JSONArray from a source JSON text. // @param source A string that begins with // <code>[</code>&nbsp;<small>(left bracket)</small> // and ends with <code>]</code>&nbsp;<small>(right bracket)</small>. // @return number of characters parsed. Return 0 if failed to parse. simcc::uint32 Parse(const string& source); // Construct a JSONArray from a source JSON text. // @param source A string that begins with // <code>[</code>&nbsp;<small>(left bracket)</small> // and ends with <code>]</code>&nbsp;<small>(right bracket)</small>. // @param source_len, the length of the source string. // if you use the default value(-1), we will use strlen(source) to // calculate the length. // @return number of characters parsed. Return 0 if failed to parse. simcc::uint32 Parse(const char* source, const simcc::int64 source_len = -1); using Object::ToString; // string ToString(bool readable = false, bool utf8_to_unicode = true) const; virtual void ToString(string& s, bool readable = false, bool utf8_to_unicode = true) const; virtual void ToStringBuf(simcc::DataStream& sb, size_t indent = 0, bool utf8_to_unicode = true) const; // @warning This method is quite not effective, so make sure why you need call this method // @note We mostly use this method to do some unit test // @return true If rhs is the same type and the value is equal to each other virtual bool Equals(const Object& rhs); // Load, Deserialize. load from data stream to convert it to a json object SIMCC_EXPORT friend simcc::DataStream& operator >> (simcc::DataStream& file, JSONObject& val); // Save, Serialize. save the json object in the data stream SIMCC_EXPORT friend simcc::DataStream& operator << (simcc::DataStream& file, const JSONObject& val); #ifdef H_PROVIDE_PROTOBUF_DEBUGSTRING_2_JSON simcc::uint32 ParseProtobuf(const string& protobuf_debug_string); #endif public: // Try to convert a string into a number, boolean, or null. If the string // can't be converted, return NULL // @note remember to delete the point , which is returned by this function // @param s A String. // @return A simple JSON value. static Object* ConvertToObject(const char* s, size_t len, JSONParser* parser, JSONTokener* x); public: // Get the object value associated with key value. // @param key the key value // @return An object value. // NULL, If there is no value for the index. Object* Get(const string& key) const; JSONBoolean* GetJSONBoolean(const string& key) const; JSONDouble* GetJSONDouble(const string& key) const; JSONInteger* GetJSONInteger(const string& key) const; JSONString* GetJSONString(const string& key) const; JSONArray* GetJSONArray(const string& key) const; JSONObject* GetJSONObject(const string& key) const; // Gets a value // @param strKey, the key // @param default_value, the default value. // @return the bool value. // or default_value, If there is no value for the key strKey bool GetBool(const string& strKey, bool default_value = false) const; float64 GetDouble(const string& strKey, float64 default_value = 0.0) const; int64 GetInteger(const string& strKey, int64 default_value = 0) const; const string& GetString(const string& strKey, const string& default_value = StringUtil::kEmpty) const; // Get a decimal number whether it is a JSONDouble or a JSONInteger simcc::float64 GetDecimal(const string& strKey, float64 default_value = 0.0) const; // Put a key/value pair into the JSONObject. // If a item which is associated with key is exist, // the old value is deleted, and the new value is inserted. // If the value is null, then the key will be removed // from the JSONObject if it is present. // @param key A key string. // @param value An object which is the value. // @return true, if successfully. // false, if failed. bool Put(const string& key, Object* value); // Do not delete this pointer, it will be managed by this JSONObject bool Put(const string& key, const ObjectPtr& value); bool Put(const string& key, const int64 value); bool Put(const string& key, const float64 value); bool Put(const string& key, const bool value); bool Put(const string& key, const string& value); bool Put(const string& key, const char* value); // Put an array to this JSONObject // @param key, the key // @param value the value array // @param count Size of array // @return true, if successfully // or false, if failed bool PutByteArray(const string& key, const simcc::int8* value, simcc::uint32 count); bool PutInt32Array(const string& key, const simcc::int32* value, simcc::uint32 count); bool PutInt64Array(const string& key, const simcc::int64* value, simcc::uint32 count); bool PutFloat32Array(const string& key, const simcc::float32* value, simcc::uint32 count); bool PutFloat64Array(const string& key, const simcc::float64* value, simcc::uint32 count); bool PutBoolArray(const string& key, const bool* value, simcc::uint32 count); bool PutStringArray(const string& key, const string* value, simcc::uint32 count); // Remove a key/value pair from this JSONObject. void Remove(const string& key) { erase(key); } void Erase(const string& key) { erase(key); } void Remove(const Object* value); void erase(iterator it) { map_.erase(it); } void erase(const string& key) { map_.erase(key); } // Returns the number of elements in the this JSON object size_t size() const { return map_.size(); } // Returns whether the JSON object is empty, i.e. whether its size is 0. bool empty() const { return map_.empty(); } // All the elements in the list container are dropped: their destructors are called, // and then they are removed from the list container, leaving it with a size of 0. void clear() { map_.clear(); } // Merge another JSONObject to this JSONObject // For example: // A : { "keyA1" : "valueA1", "keyA2" : "valueA2", "same-key" : "old value" } // B : { "keyB1" : "valueB", "same-key" : "new value from B" } // A.Merge(B, true) ==> A will change to : { "keyA1" : "valueA1", "keyA2" : "valueA2", "keyB1" : "valueB", "same-key" : "new value from B" }, // and B don't change anything. // @note If <code>rhs</code> has some same-key as this JSONObject, // this new value from <code>rhs</code> will override the original value // when <code>override</code> is true; or the value of the key in this // JSONObject will has no change. // @param rhs // @param override - void Merge(const JSONObject* rhs, bool override); // iterator public: // Gets object map container. const ObjectPtrMap& GetObjects() const { return map_; } // Gets object map container. ObjectPtrMap& GetObjects() { return map_; } const_iterator begin() const { return map_.begin(); } iterator begin() { return map_.begin(); } const_iterator end() const { return map_.end(); } iterator end() { return map_.end(); } const_reverse_iterator rbegin() const { return map_.rbegin(); } reverse_iterator rbegin() { return map_.rbegin(); } const_reverse_iterator rend() const { return map_.rend(); } reverse_iterator rend() { return map_.rend(); } protected: // Produce a string in simcc::f64 quotes with backslash sequences in all the // right places. A backslash will be inserted within </, allowing JSON // text to be delivered in HTML. In JSON text, a string cannot contain a // control character or an unescaped quote or backslash. // @param source A the source String // @param rs the produced string by this function // @return true, if success, or false static void Quote(const string& source, bool utf8_to_unicode, simcc::DataStream& sb); template<class T> bool PutIntegerArray(const string& key, const T* value, simcc::uint32 count); friend class JSONTokener; friend class JSONArray; friend class JSONString; friend class JSONDouble; friend class JSONInteger; friend class JSONBoolean; friend class JSONNull; // Return number of characters parsed. simcc::uint32 Parse(JSONTokener* token); JSONObject(JSONTokener* token); private: friend class JSONParser; // override method from base class json::Object virtual bool LoadFrom(simcc::DataStream& file); virtual void SaveTo(simcc::DataStream& file) const; private: ObjectPtrMap map_; }; typedef simcc::RefPtr<JSONObject> JSONObjectPtr; typedef simcc::RefPtr<JSONInteger> JSONIntegerPtr; typedef simcc::RefPtr<JSONDouble> JSONDoublePtr; typedef simcc::RefPtr<JSONArray> JSONArrayPtr; typedef simcc::RefPtr<JSONString> JSONStringPtr; typedef simcc::RefPtr<JSONBoolean> JSONBooleanPtr; typedef simcc::RefPtr<JSONNull> JSONNullPtr; typedef simcc::RefPtr<Object> ObjectPtr; } }
pengdao/simcc
simcc/inner_pre.h
#pragma once #include "platform_config.h" #ifndef H_CASE_STRING_BIGIN #define H_CASE_STRING_BIGIN(state) switch(state) { #define H_CASE_STRING(state) case state: return #state; break; #define H_CASE_STRING_END() default: return "Unknown"; break; } #endif #include <string> namespace simcc { using std::string; using std::wstring; typedef uint64_t uint64; typedef int64_t int64; typedef uint32_t uint32; typedef int32_t int32; typedef uint16_t uint16; typedef int16_t int16; typedef uint8_t uint8; typedef int8_t int8; typedef float float32; typedef double float64; }
pengdao/simcc
simcc/handler_guard.h
#pragma once #include <functional> namespace simcc { class HandlerGuard { public: typedef std::function<void()> Handler; public: HandlerGuard(Handler h) : cb_(h), execute_(true) {} ~HandlerGuard() { if (execute_) { cb_(); } } void set_execute(bool v) { execute_ = v; } private: Handler cb_; bool execute_; }; }
pengdao/simcc
simcc/misc/crc32.h
<gh_stars>100-1000 #pragma once #include "simcc/inner_pre.h" #include <stdint.h> #include <string> namespace simcc { class SIMCC_EXPORT CRC32 { public: // @brief // @param d Source data buffer, If length is length than dwLength, result is unknown. // @param len The size of d. // @return crc value. static uint32_t Sum(const void* d, size_t len); static uint32_t Sum(const string& s) { return Sum(s.data(), s.size()); } private: // Initialize the CRC table with 256 elements. static void InitTable(uint32_t* table); static uint32_t Reflect(uint32_t ref, char ch); }; }
pengdao/simcc
simcc/type_traits.h
#pragma once #include "platform_config.h" #include <type_traits> #define H_IS_POD_TYPE( type , booltype ) namespace std { \ template<> \ struct is_pod<type> : public booltype##_type {}; \ }
pengdao/simcc
simcc/platform_config.h
#pragma once #ifdef _DEBUG #ifndef H_DEBUG_MODE #define H_DEBUG_MODE #endif #endif #include <assert.h> #include <stdint.h> #ifdef __cplusplus #include <iostream> #include "gettimeofday.h" #include <memory> #include <functional> #endif // end of define __cplusplus // from google3/base/basictypes.h // The H_ARRAYSIZE(arr) macro returns the # of elements in an array arr. // The expression is a compile-time constant, and therefore can be // used in defining new arrays, for example. // // H_ARRAYSIZE catches a few type errors. If you see a compiler error // // "warning: division by zero in ..." // // when using H_ARRAYSIZE, you are (wrongfully) giving it a pointer. // You should only use H_ARRAYSIZE on statically allocated arrays. // // The following comments are on the implementation details, and can // be ignored by the users. // // ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in // the array) and sizeof(*(arr)) (the # of bytes in one array // element). If the former is divisible by the latter, perhaps arr is // indeed an array, in which case the division result is the # of // elements in the array. Otherwise, arr cannot possibly be an array, // and we generate a compiler error to prevent the code from // compiling. // // Since the size of bool is implementation-defined, we need to cast // !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final // result has type size_t. // // This macro is not perfect as it wrongfully accepts certain // pointers, namely where the pointer size is divisible by the pointer // size. Since all our code has to go through a 32-bit compiler, // where a pointer is 4 bytes, this means all pointers to a type whose // size is 3 or greater than 4 will be (righteously) rejected. // // Kudos to <NAME> for this simple and elegant implementation. #undef H_ARRAYSIZE #define H_ARRAYSIZE(a) \ ((sizeof(a) / sizeof(*(a))) / \ static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) /* * Sizes for buffers used by the _makepath() and _splitpath() functions. * note that the sizes include space for 0-terminator */ #ifndef _MAX_PATH # define _MAX_PATH 260 /* max. length of full pathname */ #endif #include "windows_port.h"
pengdao/simcc
simcc/timestamp.inl.h
#pragma once #include "gettimeofday.h" namespace simcc { inline Timestamp::Timestamp() : ns_(0) {} inline Timestamp::Timestamp(int64_t nanoseconds) : ns_(nanoseconds) {} inline bool Timestamp::IsEpoch() const { return ns_ == 0; } inline Timestamp::Timestamp(const struct timeval& t) : ns_(int64_t(t.tv_sec) * Duration::kSecond + t.tv_usec * Duration::kMicrosecond) {} inline Timestamp Timestamp::Now() { struct timeval tv; gettimeofday(&tv, NULL); int64_t ns = int64_t(tv.tv_sec) * Duration::kSecond + int64_t(tv.tv_usec) * Duration::kMicrosecond; return Timestamp(ns); } inline void Timestamp::Add(Duration d) { ns_ += d.Nanoseconds(); } inline void Timestamp::To(struct timeval* t) const { t->tv_sec = (long)(ns_ / Duration::kSecond); t->tv_usec = (long)(ns_ % Duration::kSecond) / (long)Duration::kMicrosecond; } inline struct timeval Timestamp::TimeVal() const { struct timeval t; To(&t); return t; } inline int64_t Timestamp::Unix() const { return ns_ / Duration::kSecond; } inline int64_t Timestamp::UnixNano() const { return ns_; } inline bool Timestamp::operator<(const Timestamp& rhs) const { return ns_ < rhs.ns_; } inline bool Timestamp::operator==(const Timestamp& rhs) const { return ns_ == rhs.ns_; } inline Timestamp Timestamp::operator+=(const Duration& rhs) { ns_ += rhs.Nanoseconds(); return *this; } inline Timestamp Timestamp::operator+(const Duration& rhs) const { Timestamp temp(*this); temp += rhs; return temp; } inline Timestamp Timestamp::operator-=(const Duration& rhs) { ns_ -= rhs.Nanoseconds(); return *this; } inline Timestamp Timestamp::operator-(const Duration& rhs) const { Timestamp temp(*this); temp -= rhs; return temp; } inline Duration Timestamp::operator-(const Timestamp& rhs) const { int64_t ns = ns_ - rhs.ns_; return Duration(ns); } } // namespace simcc
pengdao/simcc
simcc/misc/crc16.h
#pragma once #include "simcc/inner_pre.h" #include <stdint.h> #include <string> namespace simcc { // CRC-16/CCITT class SIMCC_EXPORT CRC16 { public: static uint16_t Sum(const void* data, size_t len); static uint16_t Sum(const string& s) { return Sum(s.data(), s.size()); } }; }
pengdao/simcc
simcc/misc/md5.h
<reponame>pengdao/simcc<gh_stars>100-1000 #pragma once #include "simcc/inner_pre.h" #include "php_md5.h" #include <fstream> #include <iostream> namespace simcc { // A wrapper of PHP md5 implementation class SIMCC_EXPORT MD5 { public: enum { kBinDigestLength = 16, // the length of digest as a 16-byte binary array kHexDigestLength = 32, // the length of digest as a 32-byte ASCII-hex string, not include the terminating null-character }; public: MD5() { PHP_MD5Init(&md5_ctx); } void Update(const void* data, size_t data_len) { PHP_MD5Update(&md5_ctx, (const unsigned char*)data, data_len); } template<typename string_t> void Update(const string_t& data) { Update(data.data(), data.size()); } void Finalize(unsigned char binary16_digest[/*16*/]) { PHP_MD5Final(binary16_digest, &md5_ctx); } void Finalizeh(char hex33[33]); string Finalize() { string m(kBinDigestLength, '\0'); Finalize((unsigned char*)&m[0]); return m; } string Finalizeh() { string m(kHexDigestLength, '\0'); Finalize((unsigned char*)&m[0]); //m.resize(kHexDigestLength); return m; } // static helpful utility methods public: // Calculate the MD5 checksum of the data. static void Sum(const void* data, size_t data_len, unsigned char binary16_digest[16]); static string Sum(const void* data, size_t data_len); static string Sum(const string& d); // Calculate the MD5 checksum of the data. The checksum is human readable with 32 bytes hex code. static void Sumh(const void* data, size_t data_len, char hex33[/*33*/]); static string Sumh(const void* data, size_t data_len); static string Sumh(const string& d); // Generate a random md5 // @return a random hex md5, 32 bytes static string GenHexMD5(const size_t random_data_len = 8); // @return a random binary md5, 16 bytes static string GenBinMD5(const size_t random_data_len = 8); // @brief Convert a binary buffer to a hex format // @param[in] binary - // @param[in] binary_len - // @param[in] hex - At least with length of binary_len*2 // @return void - static void Bin2Hex(const void* binary, size_t binary_len, char* hex); static string Bin2Hex(const void* binary, size_t binary_len); // @brief Convert a hex format buffer to binary // @param[in] hex - // @param[in] hex_len - // @param[in] binary - At least with length of hex_len/2 // @return bool - static bool Hex2Bin(const char* hex, const size_t hex_len, void* binary); static string Hex2Bin(const char* hex, const size_t hex_len); static int DehexChar(char c); static bool IsValid(const char* hexmd5, size_t hexmd5_length); static bool IsValid(const string& hexmd5); private: PHP_MD5_CTX md5_ctx; }; inline void MD5::Finalizeh(char hex33[33]) { unsigned char binary16_digest[kBinDigestLength]; PHP_MD5Final(binary16_digest, &md5_ctx); Bin2Hex(binary16_digest, kBinDigestLength, hex33); } inline void MD5::Sum(const void* data, size_t data_len, unsigned char binary16_digest[16]) { PHP_MD5_CTX ctx; PHP_MD5Init(&ctx); PHP_MD5Update(&ctx, (const unsigned char*)data, data_len); PHP_MD5Final(binary16_digest, &ctx); } inline string MD5::Sum(const string& d) { return Sum(d.data(), d.size()); } inline void MD5::Sumh(const void* data, size_t data_len, char hex33[/*33*/]) { PHP_MD5_CTX ctx; PHP_MD5Init(&ctx); PHP_MD5Update(&ctx, (const unsigned char*)data, data_len); unsigned char* binary = reinterpret_cast<unsigned char*>(hex33 + kBinDigestLength); PHP_MD5Final(binary, &ctx); Bin2Hex(binary, kBinDigestLength, hex33); } inline string MD5::Sumh(const string& d) { return Sumh(d.data(), d.size()); } inline string MD5::Sum(const void* data, size_t data_len) { string binary16_digest; binary16_digest.resize(16); Sum(data, data_len, reinterpret_cast<unsigned char*>(&binary16_digest[0])); return binary16_digest; } inline string MD5::Sumh(const void* data, size_t data_len) { string hex33; hex33.resize(kHexDigestLength + 1); Sumh(data, data_len, &hex33[0]); hex33.resize(kHexDigestLength); return hex33; } inline void MD5::Bin2Hex(const void* binary, size_t binary_len, char* hex) { int m = 0; const uint8_t* ubinary = reinterpret_cast<const uint8_t*>(binary); for (size_t i = 0; i < binary_len; ++i) { m = (ubinary[i] & 0xF0) >> 4; if (m <= 9) { hex[i << 1] = m + '0'; } else { hex[i << 1] = m + 'a' - 10; } m = (ubinary[i]) & 0x0F; if (m <= 9) { hex[(i << 1) + 1] = m + '0'; } else { hex[(i << 1) + 1] = m + 'a' - 10; } } hex[binary_len << 1] = '\0'; } inline string MD5::Bin2Hex(const void* binary, size_t binary_len) { string r; r.resize(binary_len << 1); Bin2Hex(binary, binary_len, &r[0]); return r; } inline bool MD5::Hex2Bin(const char* hex, const size_t hex_len, void* binary) { int m = 0; uint8_t* ubinary = reinterpret_cast<uint8_t*>(binary); size_t i = 0; size_t hex_len_1 = hex_len - 1; while (i < hex_len_1) { m = DehexChar(hex[i]); if (m < 0) { return false; } ubinary[i >> 1] = m << 4; m = DehexChar(hex[i + 1]); if (m < 0) { return false; } ubinary[i >> 1] |= m; i += 2; } return true; } inline string MD5::Hex2Bin(const char* hex, const size_t hex_len) { string r; r.resize(hex_len >> 1); Hex2Bin(hex, hex_len, &r[0]); return r; } inline int MD5::DehexChar(char c) { static int hex2dec_table[256] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ /* 0 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 1 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 2 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1, /* 4 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 5 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 6 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 7 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 8 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 9 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* A */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* B */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* C */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* D */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* E */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* F */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1 }; return hex2dec_table[(int)c]; } inline bool MD5::IsValid(const char* hexmd5, size_t hexmd5_length) { if (hexmd5_length > 32 || hexmd5_length == 0) { return false; } static const char valid_chars[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (size_t i = 0; i < hexmd5_length; ++i) { if (valid_chars[(int)hexmd5[i]] == 0) { return false; } } return true; } inline bool MD5::IsValid(const string& hexmd5) { return IsValid(hexmd5.c_str(), hexmd5.length()); } } // simcc
pengdao/simcc
simcc/json/json.h
<reponame>pengdao/simcc // Created: 2009/08/07 // Author: weizili #pragma once #include "json_common.h" #include "json_parser.h" #include "json_cast.h" #include "json_value.h" #include "json_array.h" #include "json_object.h" #include "inherited_conf_json.h"
pengdao/simcc
simcc/json/json_array.h
<gh_stars>100-1000 // Created: 2009/08/07 // Author: weizili #pragma once #include "simcc/inner_pre.h" #include "simcc/gcc_list.h" #include "json_common.h" #include "json_value.h" #include "json_parser.h" namespace simcc { namespace json { // A JSONArray is an ordered sequence of values. Its external text form is a // string wrapped in square brackets with commas separating the values. The // internal form is an object. class JSONObject; class JSONTokener; class SIMCC_EXPORT JSONArray : public Object, public JSONParser { public: typedef simcc::list<ObjectPtr> ObjectPtrList; typedef ObjectPtrList::iterator iterator; typedef ObjectPtrList::const_iterator const_iterator; typedef ObjectPtrList::reverse_iterator reverse_iterator; typedef ObjectPtrList::const_reverse_iterator const_reverse_iterator; public: enum { Type = kJSONArray }; // Construct an empty JSONArray. JSONArray() : Object(kJSONArray) {} virtual ~JSONArray(); // Construct a JSONArray from a source JSON text. // @param source A string that begins with // <code>[</code>&nbsp;<small>(left bracket)</small> // and ends with <code>]</code>&nbsp;<small>(right bracket)</small>. // @return number of characters parsed. Return 0 if failed to parse. uint32 Parse(const string& source); // Construct a JSONArray from a source JSON text. // @param source A string that begins with // <code>[</code>&nbsp;<small>(left bracket)</small> // and ends with <code>]</code>&nbsp;<small>(right bracket)</small>. // @param source_len, the length of the source string. // if you use the default value(-1), we will use strlen(source) to // calculate the length. // @return number of characters parsed. Return 0 if failed to parse. uint32 Parse(const char* source, const int64 source_len = -1); // Get the object value associated with an index. // @param index // The index must be between 0 and length() - 1. // @return An object value. // NULL, If there is no value for the index. Object* Get(int index) const; JSONBoolean* GetJSONBoolean(int index) const; JSONDouble* GetJSONDouble(int index) const; JSONInteger* GetJSONInteger(int index) const; JSONString* GetJSONString(int index) const; JSONArray* GetJSONArray(int index) const; JSONObject* GetJSONObject(int index) const; bool IsNull(int index) const; // Gets a value // @param strKey, the key // @param default_value, the default value. // @return the bool value. // or default_value, If there is no value for the key strKey bool GetBool(int index, bool default_value = false) const; float64 GetDouble(int index, float64 default_value = 0) const; int64 GetInteger(int index, int64 default_value = 0) const; const string& GetString(int index, const string& default_value = StringUtil::kEmpty) const; // Get a decimal number whether it is a JSONDouble or a JSONInteger float64 GetDecimal(int index, float64 default_value = 0.0)const; // Gets an array. // @param strKey, the key // @param array[out] the result is stored // @param count Size of array // @param default_value, the default value of the array element // @return true, if found the key strKey // or false, If there is no value for the key strKey void GetBoolArray(bool* array, simcc::uint32 count, bool default_value = false)const; void GetByteArray(simcc::uint8* array, simcc::uint32 count, simcc::uint8 default_value = 0)const; void GetInt32Array(simcc::int32* array, simcc::uint32 count, simcc::int32 default_value = 0)const; void GetInt64Array(simcc::int64* array, simcc::uint32 count, simcc::int64 default_value = 0)const; void GetFloat32Array(simcc::float32* array, simcc::uint32 count, simcc::float32 default_value = 0.0f)const; void GetFloat64Array(simcc::float64* array, simcc::uint32 count, simcc::float64 default_value = 0.0)const; void GetStringArray(string* array, simcc::uint32 count, const string& default_value = StringUtil::kEmpty)const; // Gets an array. // @remark Try to find typed value, of can not find,set default value. // @param strKey, the key // @param vec[out] the result is stored void GetBoolArray(std::vector<bool>& vec, bool default_value = false)const; void GetByteArray(std::vector<simcc::uint8>& vec, simcc::uint8 default_value = 0)const; void GetInt32Array(std::vector<simcc::int32>& vec, simcc::int32 default_value = 0)const; void GetInt64Array(std::vector<simcc::int64>& vec, simcc::int64 default_value = 0)const; void GetFloat32Array(std::vector<simcc::float32>& vec, simcc::float32 default_value = 0.0f)const; void GetFloat64Array(std::vector<simcc::float64>& vec, simcc::float64 default_value = 0.0)const; void GetStringArray(std::vector<string>& vec, const string& default_value = StringUtil::kEmpty)const; // Append a value. This increases the array's length by one. // // @param value A boolean/double/int64/string/Object value. // @return this. JSONArray* Put(const bool value); JSONArray* Put(const simcc::float64 value); JSONArray* Put(const simcc::int64 value); JSONArray* Put(const string& s); JSONArray* Put(const char* s); JSONArray* Put(Object* value); // Do not delete this pointer, it will be managed by this JSONArray JSONArray* Put(const ObjectPtr& value); // Remove a index and close the hole. // @param index The index of the element to be removed. // @return true if remove the element success bool Remove(int index); // Returns whether the JSON object is empty, i.e. whether its size is 0. bool empty() const { return list_.empty(); } // All the elements in the list container are dropped, their destructors are called, // and then they are removed from the list container, leaving it with a size of 0. void clear() { list_.clear(); } iterator erase(iterator it) { return list_.erase(it); } // Get the number of elements in the JSONArray, included nulls. // @return The length (or size). size_t size() const { return list_.size(); } // Make a JSON text of this JSONArray. For compactness, no // unnecessary whitespace is added. If it is not possible to produce a // syntactically correct JSON text then null will be returned instead. This // could occur if the array contains an invalid number. // <p> // @warning This method assumes that the data structure is a cyclical. // @override override method from base class json::Object // @return a printable, displayable, transmittable // representation of the array. using Object::ToString; // string ToString(bool readable = false, bool utf8_to_unicode = true) const; virtual void ToString(string& s, bool readable = false, bool utf8_to_unicode = true)const; virtual void ToStringBuf(simcc::DataStream& sb, size_t indent = 0, bool utf8_to_unicode = true)const; // @warning This method is quite not effective, so make sure why you need call this method // @note We mostly use this method to do some unit test // @return true If rhs is the same type and the value is equal to each other virtual bool Equals(const Object& rhs); // iterator public: // Gets objects in the array. // @remark Caller is responsible for identify the concrete type of object element. const ObjectPtrList& GetObjects()const { return list_; } const_iterator begin() const { return list_.begin(); } iterator begin() { return list_.begin(); } const_iterator end() const { return list_.end(); } iterator end() { return list_.end(); } const_reverse_iterator rbegin() const { return list_.rbegin(); } reverse_iterator rbegin() { return list_.rbegin(); } const_reverse_iterator rend() const { return list_.rend(); } reverse_iterator rend() { return list_.rend(); } protected: friend class JSONTokener; friend class JSONObject; friend class JSONParser; // @return number of characters parsed. Return 0 if failed to parse. simcc::uint32 Parse(JSONTokener* token); JSONArray(JSONTokener* token); // Construct a JSONArray from a source JSON text string. // @note Don't use this tow constructors, unless you can make sure // the json text string is valid format. You can you JSONArray() // instead, and use Parse(...) method to build a JSON object // from a json text string. // @param source A source json text string JSONArray(const string& source); JSONArray(const char* source); template<class T> const T& GetElement(int index, const T& default_value)const; template<class T, class U> void GetElement(T*, uint32 count, const U& default_value)const; template<class T, class U> void GetElement(std::vector<T>& vec, const U& default_value)const; private: // override method from base class json::Object virtual bool LoadFrom(simcc::DataStream& file); virtual void SaveTo(simcc::DataStream& file) const; private: ObjectPtrList list_; // The list where the JSONArray's properties are kept. template<class T> T* GetObject(int index) const; private: const_iterator begin(size_t index) const; iterator begin(size_t index); }; //end of class typedef simcc::RefPtr<JSONArray> JSONArrayPtr; } }
pengdao/simcc
simcc/json/json_common.h
// Created: 2009/08/07 // Author: weizili #pragma once #include "simcc/inner_pre.h" #include "simcc/ref_object.h" #include "simcc/string_util.h" #include "simcc/data_stream.h" namespace simcc { namespace json { enum JSONType { kUnknownType = 0, kJSONObject, // JSONObject kJSONArray, // JSONArray kJSONString, // JSONString kJSONInteger, // JSONInteger kJSONDouble, // JSONDouble kJSONBoolean, // JSONBoolean kJSONNull, // JSONNull kTypeForce = 0xFF // bitwise-and with mask of 0xFF can be optimized by compiler }; class JSONBoolean; class JSONInteger; class JSONDouble; class JSONString; class JSONArray; class JSONObject; class JSONTokener; template<typename _Type> struct ToJSONType; template<> struct ToJSONType<bool> { typedef JSONBoolean JSONClass; enum { Type = kJSONBoolean }; }; template<> struct ToJSONType<simcc::int64> { typedef JSONInteger JSONClass; enum { Type = kJSONInteger }; }; template<> struct ToJSONType<simcc::float64> { typedef JSONDouble JSONClass; enum { Type = kJSONDouble }; }; template<> struct ToJSONType<string> { typedef JSONString JSONClass; enum { Type = kJSONString }; }; template<> struct ToJSONType<JSONArray> { typedef JSONArray JSONClass; enum { Type = kJSONArray }; }; template<> struct ToJSONType<JSONObject> { typedef JSONObject JSONClass; enum { Type = kJSONObject }; }; // Abstract class of all json Objects : // JSONObject, JSONArray, JSONString, JSONInteger, JSONDouble, JSONBoolean, JSONNull class SIMCC_EXPORT Object : public simcc::RefObject { public: enum { Type = kUnknownType }; Object(JSONType e) : type_(e) {} virtual ~Object() {} JSONType type() const { return type_; } bool IsTypeOf(JSONType ot) const { return (ot == type_); } // @brief // @param[in] readable, true, to make a pretty printed JSON text of this object. // false, to make a compact JSON text, no whitespace is added. // @param[in] utf8_to_unicode - true to guaranteed to consist only of ASCII characters. This is archived by escaping all Unicode characters outside the ASCII range // @return the json text string string ToString(bool readable = false, bool utf8_to_unicode = true) const; // Make a JSON text of an Object value. the result is stored in outs // e.g. string "abc" => "\"abc\"" // e.g. string "ab\t" => "\"ab\\t\"" // e.g. int 324 => "324" // @param[out] outs - the json text string // @param[in] readable - true, to make a pretty printed JSON text of this object. // false, to make a compact JSON text, no whitespace is added. // @param[in] utf8_to_unicode - true to guaranteed to consist only of ASCII characters. This is achieved by escaping all Unicode characters outside the ASCII range // @return true, if success, or false virtual void ToString(string& outs, bool readable = false, bool utf8_to_unicode = true) const = 0; virtual void ToStringBuf(simcc::DataStream& sb, size_t indent = 0, bool utf8_to_unicode = true) const = 0; // @warning This method is quite not effective, so make sure why you need call this method // @note We mostly use this method to do some unit test // @return true if rhs is the same type and the value is equal to each other virtual bool Equals(const Object& rhs) = 0; protected: // Load, Deserialize. load from data stream to convert it to a json object // Before we call this function, we has deserialized the a simcc::u8 // as the type, so we just deserialize the data in this function // and don't care about the first simcc::uint8 type. virtual bool LoadFrom(simcc::DataStream& file) = 0; // Save, Serializer. save the json object in the data stream // we first save the type as a simcc::uint8 in the file and then save the data. virtual void SaveTo(simcc::DataStream& file) const = 0; protected: // Deserialize the data stream to parse one json object. // First we deserialize a type and then deserialize an object according to the type. // @param file[in] the binary data stream // @param pObject[out] the parsed json object // @return true, if load a json object successfully, you need to take over the memory delete of pObject, or false. static bool DeserializeOneObject(simcc::DataStream& file, Object*& pObject); private: JSONType type_; private: // we need to access SaveTo, LoadFrom friend class JSONArray; friend class JSONObject; Object(); }; typedef simcc::RefPtr<Object> ObjectPtr; } }
pengdao/simcc
simcc/http_data_parser.h
<gh_stars>100-1000 #pragma once #include "memmem.h" #include "slice.h" #include "ini_parser.h" namespace simcc { class URIParser { public: typedef std::map<std::string, std::string> ssmap; template<class _TMAP> static bool Parse(const char* d, size_t dlen, _TMAP& kv) { #ifdef H_OS_WINDOWS const char* p = strchr((char*)d, '?'); #else const char* p = strchr(d, '?'); #endif if (!p) { return true; } if (p >= d + dlen) { return true; } int32_t len = (int32_t)dlen + d - p - 1; if (len <= 0) { return true; } bool r = true; INIParser ini; ini.set_compatible(true); if (!ini.Parse(p + 1, len, "&", "=")) { r = false; } kv.insert(ini.GetDefaultKeyValueMap().begin(), ini.GetDefaultKeyValueMap().end()); return r; } template<class _TMAP> static bool Parse(const char* d, size_t dlen, std::string& uri, _TMAP* kv) { #ifdef H_OS_WINDOWS const char* p = strchr((char*)d, '?'); #else const char* p = strchr(d, '?'); #endif if (!p) { uri.assign(d, dlen); return true; } if (p >= d + dlen) { uri.assign(d, dlen); return true; } uri.assign(d, p - d); int32_t len = (int32_t)dlen + d - p - 1; if (len <= 0) { return true; } if (!kv) { return true; } bool r = true; INIParser ini; ini.set_compatible(true); if (!ini.Parse(p + 1, len, "&", "=")) { r = false; } kv->insert(ini.GetDefaultKeyValueMap().begin(), ini.GetDefaultKeyValueMap().end()); return r; } }; class HttpMultiDataParser { #ifndef CRLF #define CRLF "\x0d\x0a" #endif public: typedef std::map<std::string, std::string> ssmap; template<class _T_string, class _TMAP> static bool Parse(const void* d, size_t dlen, _TMAP& kv) { const char* end = (const char*)d + dlen; const char* p = (const char*)d; static std::string tag_name_prefix = "Content-Disposition: form-data; name=\""; static std::string tag_kvsep = CRLF CRLF; static std::string tag_value_end = CRLF "-----------------------------"; while (p < end) { const char* found = static_cast<const char*>(memmem(p, end - p, tag_name_prefix.data(), tag_name_prefix.size())); if (!found || found >= end) { break; } found += tag_name_prefix.size(); if (found >= end) { break; } p = found; while (p < end && *p != '"') ++p; if (p >= end) { break; } if (p <= found) { continue; } _T_string key(found, p - found); if (memcmp(p + 1, tag_kvsep.data(), tag_kvsep.size()) != 0) { //continue; return false;//TODO strict check } const char* value = p + 1 + tag_kvsep.size(); if (value >= end) { break; } p = value; found = static_cast<const char*>(memmem(p, end - p, tag_value_end.data(), tag_value_end.size())); if (!found || found >= end) { break; } { _T_string& v = kv[key]; if (v.empty()) { v = _T_string(value, found - value); } } p = value; } return true; } template<class _T_string, class _TMAP> static bool Parse(const void* d, size_t dlen, const std::string& http_multipart_boundary, _TMAP& kv) { const char* end = (const char*)d + dlen; const char* p = (const char*)d; static std::string tag_name_prefix = "Content-Disposition: form-data; name=\""; static std::string tag_kvsep = CRLF CRLF; std::string tag_value_end(http_multipart_boundary.size() + 2 + 2, 0); tag_value_end = CRLF; tag_value_end.append("--", 2).append(http_multipart_boundary); while (p < end) { const char* found = static_cast<const char*>(memmem(p, end - p, tag_name_prefix.data(), tag_name_prefix.size())); if (!found || found >= end) { break; } found += tag_name_prefix.size(); if (found >= end) { break; } p = found; while (p < end && *p != '"') ++p; if (p >= end) { break; } if (p <= found) { continue; } _T_string key(found, p - found); if (memcmp(p + 1, tag_kvsep.data(), tag_kvsep.size()) != 0) { //continue; return false;//TODO strict check } const char* value = p + 1 + tag_kvsep.size(); if (value >= end) { break; } p = value; found = static_cast<const char*>(memmem(p, end - p, tag_value_end.data(), tag_value_end.size())); if (!found || found >= end) { break; } { _T_string& v = kv[key]; if (v.empty()) { v = _T_string(value, found - value); } } p = value; } return true; } template<class _T_string> static bool Extract(const void* d, size_t dlen, const _T_string& key, _T_string& out_value) { const char* end = (const char*)d + dlen; const char* p = (const char*)d; static std::string tag_name_prefix = "Content-Disposition: form-data; name=\""; static std::string tag_kvsep = CRLF CRLF; static std::string tag_value_end = CRLF "-----------------------------"; while (p < end) { const char* found = static_cast<const char*>(memmem(p, end - p, tag_name_prefix.data(), tag_name_prefix.size())); if (!found || found >= end) { break; } found += tag_name_prefix.size(); if (found >= end) { break; } p = found; while (p < end && *p != '"') ++p; if (p >= end) { break; } if (p <= found) { continue; } if (memcmp(p + 1, tag_kvsep.data(), tag_kvsep.size()) != 0) { continue; } const char* value_begin = p + 1 + tag_kvsep.size(); if (value_begin >= end) { break; } if (memcmp(key.data(), found, p - found) != 0) { continue; } p = value_begin; found = static_cast<const char*>(memmem(p, end - p, tag_value_end.data(), tag_value_end.size())); if (!found || found >= end) { break; } out_value = _T_string(value_begin, found - value_begin); return true; } return false; } // 若 http 头未传入 // 硬解获取 http_multipart_boundary // // --yQmSenn8dvtLUKEV8bRcq8uiATfXEf5H^M$ // Content-Disposition: form-data; name="Fileinfo"^M$ // ^M$ // [CONTENT]^M$ // --yQmSenn8dvtLUKEV8bRcq8uiATfXEf5H--^M$ static bool GetBoundary(const void* d, size_t dlen, std::string& http_multipart_boundary) { static std::string tag_name_prefix = "Content-Disposition:"; const char* end = (const char*)d + dlen; const char* p = (const char*)d; std::string tag_value_end(tag_name_prefix.size() + 2, 0); tag_value_end = CRLF; tag_value_end.append(tag_name_prefix); const char* found = static_cast<const char*>(memmem(p, end - p, tag_value_end.data(), tag_value_end.size())); if (!found || found >= end) { return false; } std::string multipart_boundary(p + 2, found - p - 2); // find end multipart_boundary std::string end_multipart_boundary(multipart_boundary.size() +2, 0); end_multipart_boundary = multipart_boundary; end_multipart_boundary.append("--", 2); found = static_cast<const char*>(memmem(end - 128, 128, end_multipart_boundary.data(), end_multipart_boundary.size())); if (!found || found >= end) { return false; } http_multipart_boundary.swap(multipart_boundary); return true; } }; }
pengdao/simcc
simcc/tokener.h
#pragma once #include "simcc/inner_pre.h" #include "simcc/slice.h" namespace simcc { // A Tokener takes a source string and extracts characters and tokens from it. // It is used to help to parse strings. class Tokener { public: Tokener() { Reset("", 0); } Tokener(const string& s); Tokener(const char* ps, const int32 ps_len = -1); // Calling this method is similar to reconstruct a new Tokener void Reset(const char* ps, const int32 ps_len = -1); ~Tokener(); // Back up one character. This provides a sort of lookahead capability, // so that you can test for a digit or letter before attempting to parse // the next number or identifier. bool Back(); // Back up several characters. // @param backstep - The count of back up steps bool Back(int backstep); // Get the next character in the source string. // This function will make the current position flag move to next position // @return The next character, or 0 if past the end of the source string. char Next(); // Get the current character in the source string. // // @return The current character, or 0 if past the end of the source string. char Current(); // Get the next char in the string, skipping whitespace. // @return A character, or 0 if there are no more characters. char NextClean(); // Get the characters up to the next character <code>quote</code>. // Backslash processing is done. // If <code>quote</code> is not found, we do nothing and just // return a string empty "". // @param quote The quoting character, either // <code>"</code>(double quote) or // <code>'</code>(single quote) or // other character // @return the string string NextString(char quote); Slice NextSlice(char quote); // Get the characters up to the next white space( or tab, \n, \r, \0 ) character. // // @return the string string NextString(); Slice NextSlice(); // Skip characters until the next character is the requested character. // If the requested character is not found, no characters are skipped. // @param to A character to skip to. // @return The requested character, or zero if the requested character // is not found. char SkipTo(char to); // Skip characters until come to a new line. // @remark If there is no new line, this function will do nothing. // @return true if successfully or false when failed. bool SkipToNextLine(); // Skip characters until the previous character is the requested character. // If the requested character is not found, no characters are skipped. // @param to A character to skip to. // @return The requested character, or zero if the requested character // is not found. char SkipBackTo(char to); // Skip all whitespace, tab, \n // @return false if arrived end of string. bool SkipSpaces(); // Get the hex value of a character (base16). // @param c A character between '0' and '9' or between 'A' and 'F' or // between 'a' and 'f'. // @return An int between 0 and 15, or -1 if c was not a hex digit. static int DehexChar(char c); // Gets current read position in the buffer. It also serve as length of buffer parsed. uint32 GetCurrentPosition() const { return current_ - data_; } // Gets current read position in the buffer. const char* GetCurrent() const { return current_; } // Query whether it is the end of the string. bool IsEnd() const { return (current_ >= end_ || *current_ == '\0'); } // Gets size of data that can read from the current read position. int32 GetReadableSize() const { return (int32)(end_ - current_); } const char* data() const { return data_; } size_t size() const { return end_ - data_; } protected: void SetCurrent(size_t pos) { current_ = data_ + pos; } void SetCurrent(const char* pos) { current_ = pos; } private: const char* data_; // the source text string to be parsed const char* current_; // At first, set it the very beginning of data_ const char* end_; // Not include the byte which is pointed by end_ }; inline Tokener::Tokener(const string& s) { Reset(s.c_str(), s.length()); } inline Tokener::Tokener(const char* ps, const int32 len) { Reset(ps, len); } inline void Tokener::Reset(const char* ps, const int32 len) { end_ = len + ps; if (len < 0 && ps) { end_ = ps + strlen(ps); } data_ = const_cast<const char*>(ps); current_ = data_; } inline Tokener::~Tokener() { } inline bool Tokener::Back() { if (current_ <= data_) { fprintf(stderr, "Stepping back two steps is not supported\n"); return false; } --current_; return true; } inline bool Tokener::Back(int backstep) { if (current_ - backstep < data_) { fprintf(stderr, "Stepping back two steps is not supported\n"); return false; } current_ -= backstep; return true; } inline int Tokener::DehexChar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; } inline char Tokener::Next() { if (IsEnd()) { // End of string ++current_; return 0; } return *current_++; } inline char Tokener::Current() { if (IsEnd()) { return 0; } return *current_; } inline char Tokener::NextClean() { for (char c = 0; current_ < end_;) { c = *current_++; /** c < 0 means This is not an ASCII character, like GBK code */ if (c > ' ' || c == 0 || c < 0) { return c; } } return 0; } inline string Tokener::NextString() { return NextSlice().ToString(); } inline Slice Tokener::NextSlice() { if (IsEnd()) { return ""; } const char* startpos = current_; for (unsigned char c = 0; current_ < end_;) { c = *current_++; if (c <= ' ') { return Slice(startpos, current_ - startpos - 1); } if (IsEnd()) { return Slice(startpos, end_ - startpos); } } assert(false && "Logic ERROR. The routine SHOULD NOT come there."); return Slice("", 0); } inline string Tokener::NextString(char quote) { return NextSlice(quote).ToString(); } inline Slice Tokener::NextSlice(char quote) { const char* startpos = current_; while (*current_++ != quote) { if (IsEnd()) { current_ = startpos; return Slice("", 0); } } assert(current_ > startpos); return Slice(startpos, current_ - startpos - 1); } inline char Tokener::SkipTo(char to) { char c = 0; const char* startIndex = this->current_; do { c = Next(); if (c == 0) { current_ = startIndex; return c; } } while (c != to); Back(); return c; } inline char Tokener::SkipBackTo(char to) { const char* startIndex = this->current_; do { if (!Back()) { current_ = startIndex; return 0; } } while (Current() != to); char c = Current(); Next(); return c; } inline bool Tokener::SkipSpaces() { for (char c = 0; current_ < end_;) { c = *current_++; if (c > ' ' || c <= 0) { Back(); return true; } else { continue; } } return false; } inline bool Tokener::SkipToNextLine() { /** * Windows line ending char is 0x0D0A * Linux/Unix line ending char is 0x0A * So, we just SkipTo(0x0A) */ char c = SkipTo((char)0x0a); if (c == 0) { return false; } // skip the last char of this line, and then go to a new line Next(); return true; } }
pengdao/simcc
simcc/ref_object.h
<reponame>pengdao/simcc<filename>simcc/ref_object.h #pragma once #include "simcc/inner_pre.h" #include <atomic> #include <algorithm> namespace simcc { // Interface provides referencing counted function. class SIMCC_EXPORT RefCountable { public: // Constructor & Destructor. RefCountable() {}; virtual ~RefCountable() {}; // Increments the reference count virtual void Ref() const = 0; // Decrements the reference count virtual void Release() const = 0; // Gets the reference count virtual int RefCount() const = 0; }; class SIMCC_EXPORT RefObject : public RefCountable { public: RefObject(): ref_count_(0) {} virtual ~RefObject() {} // Increase the reference count by 1 virtual void Ref() const; // Decrease the reference count by 1 virtual void Release() const; // Get the reference count int RefCount() const { return ref_count_; } protected: mutable std::atomic<int> ref_count_; }; // Pointer class template<class T> class RefPtr { public: typedef T object_type; protected: T* ptr_; public: RefPtr(): ptr_(0) {} RefPtr(object_type* rep) { ptr_ = rep; if (ptr_) { ptr_->Ref(); } } // Get Pointer from other type template< class U > RefPtr(U* rep) { ptr_ = dynamic_cast<object_type*>(rep); if (ptr_) { ptr_->Ref(); } } RefPtr(const RefPtr& r) { ptr_ = r.get(); if (ptr_) { ptr_->Ref(); } } template< class U > RefPtr(const RefPtr<U>& r) { ptr_ = dynamic_cast<object_type*>(r.get()); if (ptr_) { ptr_->Ref(); } } RefPtr& operator=(const RefPtr& r) { Bind(r.get()); return *this; } // assigner RefPtr& operator=(object_type* rep) { Bind(rep); return *this; } // assigner template< class U > RefPtr& operator=(const RefPtr<U>& r) { auto p = dynamic_cast<object_type*>(r.get()); assert(p); Bind(p); return *this; } ~RefPtr() { SetNull(); } operator object_type* ()const { return ptr_; } object_type& operator*() const { assert(ptr_); return *ptr_; } object_type* operator->() const { assert(ptr_); return ptr_; } bool IsNull(void) const { return ptr_ == 0; } // Bind rep to the RefPtr void Bind(object_type* rep) { if (rep) { rep->Ref(); } SetNull(); ptr_ = rep; } // Clear reference void SetNull() { if (ptr_) { T* thiz = ptr_; ptr_ = NULL; thiz->Release(); } } void Swap(simcc::RefPtr<T>& r) { std::swap(this->ptr_ , r.ptr_); } // The same interface with std::shared_ptr object_type* get() const { return ptr_; } int use_count() const; void reset(object_type* rep = NULL); }; template<class T, class U> inline bool operator==(RefPtr<T> const& a, RefPtr<U> const& b) { return a.get() == b.get(); } template<class T, class U> inline bool operator!=(RefPtr<T> const& a, RefPtr<U> const& b) { return a.get() != b.get(); } template<class T> inline int RefPtr<T>::use_count() const { if (ptr_) { return ptr_->RefCount(); } return 0; } template<class T> inline void RefPtr<T>::reset(object_type* rep /*= NULL*/) { Bind(rep); } inline void RefObject::Ref() const { ++ref_count_; } inline void RefObject::Release() const { if (--ref_count_ <= 0) { delete this; } } typedef RefPtr<RefCountable> RefPointer; typedef RefPtr<RefObject> RefObjectPtr; } #ifndef H_REFERENCE_METHODS #define H_REFERENCE_METHODS( ConcreteClass ) \ public: \ virtual void Ref() const { return ConcreteClass::Ref(); } \ virtual void Release() const { return ConcreteClass::Release(); } \ virtual int RefCount() const { return ConcreteClass::RefCount(); } #endif namespace std { template<class T> void swap(simcc::RefPtr<T>& l , simcc::RefPtr<T>& r) { return l.Swap(r); } }
pengdao/simcc
simcc/json/json_value.h
<reponame>pengdao/simcc // Created: 2009/08/07 // Author: weizili #pragma once #include "simcc/inner_pre.h" #include "json_common.h" namespace simcc { namespace json { template<class ValueType> class JSONValue : public Object { public: JSONValue() : Object(static_cast<JSONType>(ToJSONType<ValueType>::Type)) , value_(ValueType()) { } JSONValue(const ValueType& v) : Object(static_cast<JSONType>(ToJSONType<ValueType>::Type)) , value_(v) { } const ValueType& value() const { return value_; } ValueType& value() { return value_; } void set_value(const ValueType& newvalue) { value_ = newvalue; } operator ValueType& () { return value_; } protected: ValueType value_; }; // The concrete object of JSON : JSONInteger class SIMCC_EXPORT JSONInteger : public JSONValue<simcc::int64> { typedef JSONValue<simcc::int64> BaseClass; public: enum { Type = kJSONInteger }; JSONInteger(simcc::int64 v = 0); JSONInteger& operator=(simcc::int64 v); bool operator==(const JSONInteger& rhs) { return value_ == rhs.value_; } bool operator==(simcc::int64 v) { return value_ == v; } using Object::ToString; // string ToString(bool readable = false, bool utf8_to_unicode = true) const; virtual void ToString(string& s, bool readable = false, bool utf8_to_unicode = true)const; virtual void ToStringBuf(simcc::DataStream& sb, size_t indent = 0, bool utf8_to_unicode = true)const; // @warning This method is quite not effective, so make sure why you need call this method // @note We mostly use this method to do some unit test // @return true If rhs is the same type and the value is equal to each other virtual bool Equals(const Object& rhs); private: // override method from base class json::Object virtual bool LoadFrom(simcc::DataStream& file); virtual void SaveTo(simcc::DataStream& file) const; }; // The concrete object of JSON : JSONDouble class SIMCC_EXPORT JSONDouble : public JSONValue<simcc::float64> { typedef JSONValue<simcc::float64> BaseClass; public: enum { Type = kJSONDouble }; JSONDouble(simcc::float64 value = 0); JSONDouble& operator=(simcc::float64 value); bool Equals(const JSONDouble& other, simcc::float64 tolarence = 0.00001); bool Equals(simcc::float64 value, simcc::float64 tolarence = 0.00001); using Object::ToString; // string ToString(bool readable = false, bool utf8_to_unicode = true) const; virtual void ToString(string& s, bool readable = false, bool utf8_to_unicode = true)const; virtual void ToStringBuf(simcc::DataStream& sb, size_t indent = 0, bool utf8_to_unicode = true)const; // @warning This method is quite not effective, so make sure why you need call this method // @note We mostly use this method to do some unit test // @return true If rhs is the same type and the value is equal to each other virtual bool Equals(const Object& rhs); private: // override method from base class json::Object virtual bool LoadFrom(simcc::DataStream& file); virtual void SaveTo(simcc::DataStream& file) const; }; // The concrete object of JSON : JSONBoolean class SIMCC_EXPORT JSONBoolean : public JSONValue<bool> { typedef JSONValue<bool> BaseClass; public: enum { Type = kJSONBoolean }; JSONBoolean(bool value = false); JSONBoolean& operator=(bool value); bool operator==(const JSONBoolean& rhs) { return value_ == rhs.value_; } bool operator==(bool v) { return value_ == v; } using Object::ToString; // string ToString(bool readable = false, bool utf8_to_unicode = true) const; virtual void ToString(string& s, bool readable = false, bool utf8_to_unicode = true) const; virtual void ToStringBuf(simcc::DataStream& sb, size_t indent = 0, bool utf8_to_unicode = true) const; // @warning This method is quite not effective, so make sure why you need call this method // @note We mostly use this method to do some unit test // @return true If rhs is the same type and the value is equal to each other virtual bool Equals(const Object& rhs); private: // override method from base class json::Object virtual bool LoadFrom(simcc::DataStream& file); virtual void SaveTo(simcc::DataStream& file) const; }; // The concrete object of JSON : JSONString class SIMCC_EXPORT JSONString : public JSONValue<string> { typedef JSONValue<string> BaseClass; public: enum { Type = kJSONString }; JSONString(const string& value); JSONString(const char* value = ""); JSONString& operator=(const string& value); bool operator==(const JSONString& rhs) { return value_ == rhs.value_; } bool operator==(const string& v) { return value_ == v; } bool operator==(const char* v) { return value_ == v; } using JSONValue<string>::set_value; void set_value(const char* v) { value_ = v; } using Object::ToString; // string ToString(bool readable = false, bool utf8_to_unicode = true) const; virtual void ToString(string& s, bool readable = false, bool utf8_to_unicode = true)const; virtual void ToStringBuf(simcc::DataStream& sb, size_t indent = 0, bool utf8_to_unicode = true)const; // @warning This method is quite not effective, so make sure why you need call this method // @note We mostly use this method to do some unit test // @return true If rhs is the same type and the value is equal to each other virtual bool Equals(const Object& rhs); private: // override method from base class json::Object virtual bool LoadFrom(simcc::DataStream& file); virtual void SaveTo(simcc::DataStream& file) const; }; class SIMCC_EXPORT JSONNull : public Object { public: JSONNull() : Object(kJSONNull) {} using Object::ToString; // string ToString(bool readable = false, bool utf8_to_unicode = true) const; virtual void ToString(string& s, bool readable = false, bool utf8_to_unicode = true)const; virtual void ToStringBuf(simcc::DataStream& sb, size_t indent = 0, bool utf8_to_unicode = true)const; // @warning This method is quite not effective, so make sure why you need call this method // @note We mostly use this method to do some unit test // @return true If rhs is the same type and the value is equal to each other virtual bool Equals(const Object& rhs); private: // override method from base class json::Object virtual bool LoadFrom(simcc::DataStream& file); virtual void SaveTo(simcc::DataStream& file) const; }; } }
pengdao/simcc
simcc/json/json_parser.h
// Created: 2009/08/07 // Author: weizili #pragma once #include "simcc/inner_pre.h" #include "json_common.h" namespace simcc { namespace json { class SIMCC_EXPORT JSONParser { public: enum ErrorCode { kNoError = 0, kParameterWrong, kCommentFormatError, kJSONArrayNotBeginWithBrackets, //A JSONArray text must start with '[' kJSONArrayNotEndWithBrackets, //A JSONArray text must end with ']' kJSONObjectNotBeginWithBraces, //A JSONObject text must start with '{' kJSONObjectNotEndWithBraces, //A JSONObject text must start with '}' kJSONObjectKeyNotString, //A JSONObject key not a string kJSONObjectKeyIsEmpty, kInvalidCharacter, kKeyValueSeperatorError, //The key/value separator not a ':' kJSONStringNotQuoted, //A JOSNString must be quoted by "" kBlankValue, //A JSON key followed by a blank string, no value kInvalidIntegerOrDoubleString, //A invalid JSONInteger or JSONDouble string kInvalidHexadecimalCharacter, //Not a valid hexadecimal character kInvalidOctalCharacter, //Not a valid octal character kDeserializeBinaryDataError, kLoadBinaryDataError, }; public: JSONParser(); ErrorCode error() const { return error_code_; } const char* strerror() const; bool ok() const { return error() == kNoError; } size_t error_location() const { return error_location_; } public: // Construct a JSONArray or JSONObject from the source JSON text or file // @param source A string of JSON format text // @param source_len, the length of the source string. // if you use the default value(-1), we will use strlen(source) to // calculate the length. // @return JSONArray* if the <code>source</code> is a JSONArray string // or JSONObject* if the <code>source</code> is a JSONObject string // or NULL if there is some error happened which you can // use error() to get the error code static ObjectPtr Load(const char* source, const simcc::int64 source_len = -1); static ObjectPtr LoadFile(const string& json_file_path); protected: void set_error(ErrorCode ec, JSONTokener* x = NULL); void set_error(ErrorCode ec, size_t error_location); // This 3 classes will call <code>set_error</code> function friend class JSONArray; friend class JSONObject; friend class JSONTokener; mutable simcc::DataStream buf_;// The data cache buffer for the sake of improve performance private: ErrorCode error_code_; size_t error_location_;//the offset of the <code>source</code> }; } }
pengdao/simcc
simcc/file_util.h
#pragma once #include "simcc/inner_pre.h" #include <list> #include <string> #ifdef H_OS_WINDOWS #include <direct.h> #endif namespace simcc { // File access utility class which provides many help methods // to make it easy to do operations against file. class SIMCC_EXPORT FileUtil { public: // Query whether the file name is a valid directory. e.g. ".", ".." are invalid // directory name. static bool IsValidDirName(const char* name); // Query whether strFileName is a absolute path. static bool IsAbsolutePath(const string& path); // Gets absolute path name. // @param path If it is already a absolute path, we return it or else we build // a absolute path name with current path. static string GetAbsolutePathName(const string& path); // This method is copied from Golang project // Clean returns the shortest path name equivalent to path // by purely lexical processing. It applies the following rules // iteratively until no further processing can be done: // // 1. Replace multiple Separator elements with a single one. // 2. Eliminate each . path name element (the current directory). // 3. Eliminate each inner .. path name element (the parent directory) // along with the non-.. element that precedes it. // 4. Eliminate .. elements that begin a rooted path: // that is, replace "/.." by "/" at the beginning of a path, // assuming Separator is '/'. // // The returned path ends in a slash only if it represents a root directory, // such as "/" on Unix or `C:\` on Windows. // // If the result of this process is an empty string, Clean // returns the string ".". // // See also <NAME>, ``Lexical File Names in Plan 9 or // Getting Dot-Dot Right,'' // http://plan9.bell-labs.com/sys/doc/lexnames.html static string Clean(const string& path); // @brief splitting a fully qualified filename into file name and base path dir. // @param qualifiedName Path is standardized as in <code>NormalizePath</code> // @param file_name[out] // @param base_dir[out] // @param with_trailing_slash[in] true, End of the string With a SLASH "/". static void SplitFileName(const wstring& filepath, wstring& file_name, wstring& base_dir, bool with_trailing_slash = false); static void SplitFileName(const string& filepath, string& file_name, string& base_dir, bool with_trailing_slash = false); // Concatenate tow path into one, and return it. static string Join(const string& prefix, const string& postfix); static wstring Join(const wstring& prefix, const wstring& postfix); // @brief Method for standardizing paths - use forward slashes "/" only // @param filepath // @param with_trailing_slash // true, End of the string With a SLASH "/". // false, without a SLASH "/" at the end of the string // @return string static string NormalizePath(const string& filepath, bool with_trailing_slash = true); static wstring NormalizePath(const wstring& filepath, bool with_trailing_slash = true); // @brief Gets path's parent directory name. The path can be a normal file or a directory // e.g. "D:\test\aab.jpg" ==> "D:/test/" or "D:/test" // e.g. "D:/test/abc/" ==> "D:/test/" or "D:/test" // @warning The return parent director name is suitable for <code>NormalizePath</code> // That means it uses forward slash "/" as path separator // @note It take care of relative path. // @param with_trailing_slash // true, End of the string With a SLASH "/". // false, without a SLASH "/" at the end of the string // @return string, static string GetParentDir(const string& filepath, bool with_trailing_slash = true); // Gets file name without path.. // e.g. "D:/test/aab.jpg" ==> "aab.jpg" static string GetFileName(const string& filepath); // Gets base file name. the file extension will be removed. // e.g. "D:/test/aab.jpg" ==> "aab" static string GetFileNameWithoutExt(const string& filepath); // Gets file name extension. If can not find the last '.', null string // will be returned. e.g. "D:/test/aab.jpg" ==> "jpg" static string GetFileNameExtension(const string& filepath); // Gets file path name without end '/'. // e.g. "D:/test/aab.jpg" ==> "D:/test" static string GetFileDirName(const string& filepath); // Quickly remove file or directory from local file system. // @param strFileName if end with '/', it is a directory, all the children will be // remove, else is a file and the file will be removed. // @return bool True if successfully. static bool Unlink(const string& filepath) ; static bool Remove(const string& filepath) { return Unlink(filepath); } // @brief Remove the empty directory. If it is not empty or it is not directory, we do nothing and just return true. // @remark Empty directory definition: it doesn't has any normal file. // e.g. /home/a_dir/b_dir/c_dir // Condition: c_dir has no files in it, and b_dir only has c_dir and a_dir only has b_dir // If we call RemoveDirIfEmpty( "/home/a_dir/b_dir", false ), them b_dir will be deleted and its child c_dir deleted // If we call RemoveDirIfEmpty( "/home/a_dir/b_dir", true ), them a_dir, b_dir, c_dir will all be deleted. // @param recursively_delete_empty_parent_dir True, we will delete its parent directory if its parent directory is also empty // @return bool True if successfully. static bool RemoveDirIfEmpty(const string& dir, bool recursively_delete_empty_parent_dir = true); // Make directory hierarchy in local file system. // Its behavior is similar with the command 'mkdir -p' // @param dir Absolute directory file name. e.g. '/home/weizili/test' // @return true if successfully static bool Mkdir(const string& dir); static bool Rmdir(const string& dir); static bool Rmdir(const char* dir); // Determines if a file exists and could be opened. // @note The file CAN be a directory // @param filename is the string identifying the file which should be tested for existence. // @return Returns true if file exists, and false if it does not exist or an error occurred. static bool IsFileExist(const string& filepath); static bool IsReadable(const string& filepath); static bool IsWriteable(const string& filepath); static bool IsExecutable(const string& filepath); // @brief copy a file to another place. This function has the same feature like DOS Command 'copy' or Linux Command 'cp' // @warning If the destination file is exist, it will be replaced. // @warning dest_file MUST BE a file, NOT a directory // @param src_file The source file // @param src_file The target file // @param override True, this will override the old existent file. // @return bool True if successfully static bool CopyFile(const string& src_file, const string& dest_file, bool override = true) ; // @brief Query whether the given path is a directory. static bool IsDir(const char* filepath); static bool IsDir(const string& filepath); // @brief Walk the directory and get a list of files, excluded directory. // @param dir The directory path // @param files[out] The list of files are stored here. The file name is with the full path name(include the directory name) // @param recursively Whether walk the subdirectories. // @param filter Pattern to match against; which can include simple '*' wildcards static void GetFiles(const string& dir, std::list<string>& files, bool recursively = true, const string& filter = "*"); // @brief Walk the directory and get a list of files, not include directory. // @param dir The directory path // @param files[out] The list of files are stored here. The file name is with the full path name(include the directory name) // @param depth The depth to walk the subdirectories. 0 means only walk the top dir strDirName // @param filter Pattern to match against; which can include simple '*' wildcards static void GetFiles(const string& dir, std::list<string>& files, int depth, const string& filter = "*"); // Extract strings from the a file line-by-line, // every line content as a list element will be inserted to a list. static bool ReadFile(const char* filepath, std::list<string>& lines); // @brief Write the data into a file. // The file is created if it does not exist, otherwise it is truncated // @param const char* filepath - The file path where the data is stored // @param const void* content - The file content // @param const size_t len - The length of the content // @return true if successfully static bool WriteFile(const char* filepath, const void* content, const size_t len); static bool WriteFile(const string& filepath, const void* content, const size_t len); }; } #include "simcc/file_util.inl.h"
pengdao/simcc
simcc/qh_palloc.h
<gh_stars>100-1000 /* * Copyright (C) <NAME> * * Modified from ngx_palloc.{h,c} of Nginx-0.6.39 * By weizili <<EMAIL>> * Date : 2011.5.10 */ #pragma once #ifndef QIHOO_MEMORY_POOL #define QIHOO_MEMORY_POOL #endif #include <stdio.h> #define qh_align(size, boundary) (((size) + ((boundary) - 1)) & ~((boundary) - 1)) #ifndef uintptr_t #if ( defined( __linux__ ) || defined( __gnu_linux__ ) ) #include <stdint.h> typedef uint64_t uintptr_t; #endif #endif #define qh_align_ptr(p, a) \ (unsigned char*) (((uintptr_t) (p) + ((uintptr_t) a - 1)) & ~((uintptr_t) a - 1)) /* * QH_MAX_ALLOC_FROM_POOL should be (qh_pagesize - 1), i.e. 4095 on x86. * On Windows NT it decreases a number of locked pages in a kernel. */ #define QH_MAX_ALLOC_FROM_POOL (qh_pagesize - 1) #define QH_DEFAULT_POOL_SIZE (16 * 1024) #define QH_ALIGNMENT (sizeof(unsigned long)) #define QH_POOL_ALIGNMENT (16) #define QH_MIN_POOL_SIZE \ qh_align((sizeof(qh_pool_t) + 2 * sizeof(qh_pool_large_t)), \ QH_POOL_ALIGNMENT) #ifdef __cplusplus extern "C" { #endif extern int qh_pagesize; typedef void ( *qh_pool_cleanup_pt )( void *data ); typedef void* ( *qh_alloc_pt )( size_t size ); typedef void ( *qh_free_pt )( void* p ); typedef struct qh_pool_cleanup_s qh_pool_cleanup_t; typedef struct qh_pool_s qh_pool_t; typedef struct qh_pool_large_s qh_pool_large_t; typedef struct qh_str_s qh_str_t; typedef struct qh_pool_data_s qh_pool_data_t; struct qh_pool_cleanup_s { qh_pool_cleanup_pt handler; void *data; qh_pool_cleanup_t *next; }; struct qh_pool_large_s { qh_pool_large_t *next; void *alloc; }; struct qh_str_s { size_t len; unsigned char *data; }; struct qh_pool_data_s { unsigned char *last; unsigned char *end; qh_pool_t *next; unsigned int failed; }; struct qh_pool_s { qh_pool_data_t d; unsigned int max;//the max size of memory allocated from pool qh_pool_t *current; qh_pool_large_t *large; qh_pool_cleanup_t *cleanup; }; /** * @param pool_size - the pool size * @param max_alloc_from_pool - the max memory unit alloc from pool */ qh_pool_t *qh_create_pool( size_t pool_size, size_t max_alloc_from_pool /*= QH_MAX_ALLOC_FROM_POOL*/ ); void qh_destroy_pool( qh_pool_t *pool ); void qh_reset_pool( qh_pool_t *pool ); //malloc memory from qh_pool_t void *qh_palloc( qh_pool_t *pool, size_t size ); void *qh_pnalloc( qh_pool_t *pool, size_t size ); void *qh_pcalloc( qh_pool_t *pool, size_t size ); void *qh_pmemalign( qh_pool_t *pool, size_t size, size_t alignment ); int qh_pfree( qh_pool_t *pool, void *p ); qh_pool_cleanup_t *qh_pool_cleanup_add( qh_pool_t *p, size_t size ); void qh_set_alloc( qh_alloc_pt alloc_pt ); void qh_set_free( qh_free_pt free_pt ); int qh_dbgprint( const char* fmt, ... ); #ifdef __cplusplus } // end of extern "C" { #endif /** define some micro to make it no change to using Nginx code */ #define NGX_MAX_ALLOC_FROM_POOL QH_MAX_ALLOC_FROM_POOL #define NGX_DEFAULT_POOL_SIZE QH_DEFAULT_POOL_SIZE #define NGX_ALIGNMENT QH_ALIGNMENT #define NGX_POOL_ALIGNMENT QH_POOL_ALIGNMENT #define NGX_MIN_POOL_SIZE QH_MIN_POOL_SIZE #define ngx_pagesize qh_pagesize #define ngx_align qh_align #define ngx_align_ptr qh_align_ptr #define ngx_pool_cleanup_s qh_pool_cleanup_s #define ngx_pool_s qh_pool_s #define ngx_pool_large_s qh_pool_large_s #define ngx_str_s qh_str_s #define ngx_pool_data_s qh_pool_data_s #define ngx_pool_cleanup_t qh_pool_cleanup_t #define ngx_pool_t qh_pool_t #define ngx_pool_large_t qh_pool_large_t #define ngx_str_t qh_str_t #define ngx_pool_data_t qh_pool_data_t #define ngx_create_pool qh_create_pool #define ngx_destroy_pool qh_destroy_pool #define ngx_reset_pool qh_reset_pool #define ngx_palloc qh_palloc #define ngx_pnalloc qh_pnalloc #define ngx_pcalloc qh_pcalloc #define ngx_pmemalign qh_pmemalign #define ngx_pfree qh_pfree #define ngx_pool_cleanup_add qh_pool_cleanup_add #ifdef __cplusplus namespace simcc { namespace qh { class Pool { public: Pool(size_t pool_size, size_t max_alloc_from_pool = QH_MAX_ALLOC_FROM_POOL) { pool_ = qh_create_pool(pool_size, max_alloc_from_pool); } ~Pool() { qh_destroy_pool(pool_); pool_ = NULL; } qh_pool_t* pool() const { return pool_; } char* alloc(size_t len) { return static_cast<char*>(qh_palloc(pool_, len)); } void free(void* p) { qh_pfree(pool_, p); } private: qh_pool_t * pool_; }; } } #endif // end of #ifdef __cplusplus
pengdao/simcc
simcc/windows_port.h
<reponame>pengdao/simcc #pragma once // Define Operation System. #if ( defined(_WIN32) || defined(WIN64) ) # ifndef H_OS_WINDOWS # define H_OS_WINDOWS # endif # ifndef H_WINDOWS_API # define H_WINDOWS_API # endif #endif // //// Module symbol export //#ifdef H_WINDOWS_API //# ifndef H_STATIC_LIB_SIMCC //# ifdef SIMCC_EXPORTS //# define SIMCC_EXPORT __declspec(dllexport) //# else //# define SIMCC_EXPORT __declspec(dllimport) //# endif //# else //# define SIMCC_EXPORT //# endif //#else //# define SIMCC_EXPORT //#endif // #define SIMCC_EXPORT // Finds the compiler type and version. #if defined( _MSC_VER ) # ifndef H_COMPILER_MSVC # define H_COMPILER_MSVC # endif # ifndef H_COMPILER_VERSION # define H_COMPILER_VERSION _MSC_VER # endif # if H_COMPILER_VERSION < 1300 # pragma error "Not supported compiler version. Abort! Abort!" # endif #elif defined( __GNUC__ ) # ifndef H_COMPILER_GNUC # define H_COMPILER_GNUC # endif # ifndef H_COMPILER_VERSION # define H_COMPILER_VERSION (((__GNUC__)*100) + \ (__GNUC_MINOR__ * 10) + \ __GNUC_PATCHLEVEL__) # endif #else # pragma error "No known compiler. Abort! Abort!" #endif #ifdef H_OS_WINDOWS #define usleep(us) Sleep((us)/1000); #define snprintf _snprintf #define thread_local __declspec( thread ) #endif #ifdef H_OS_WINDOWS #pragma warning( disable: 4005 ) // warning C4005 : 'va_copy' : macro redefinition #pragma warning( disable: 4251 ) #pragma warning( disable: 4996 ) // warning C4996: 'strerror': This function or variable may be unsafe. Consider using strerror_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. #pragma warning( disable: 4244 4251 4355 4715 4800 4996 4005 4819) #endif // get rid of Windows/Linux inconsistencies #ifdef H_OS_WINDOWS # ifndef PRIu64 # define PRIu64 "I64u" # endif #else # ifndef PRIu64 # define PRIu64 "lu" # endif #endif #ifdef H_OS_WINDOWS # define H_LITTLE_ENDIAN #elif defined(__APPLE__) # include <machine/endian.h> #elif defined(H_OS_FREEBSD) # include <sys/endian.h> #else # include <endian.h> # if __BYTE_ORDER == __LITTLE_ENDIAN # define H_LITTLE_ENDIAN # else # define H_BIG_ENDIAN # endif #endif #ifdef H_OS_WINDOWS # define strcasecmp stricmp # define strncasecmp strnicmp #else # define stricmp strcasecmp //Linux # define strnicmp strncasecmp //Linux #endif #ifdef H_OS_WINDOWS #ifndef SIMCC_EXPORTS #pragma comment(lib, "simcc_static.lib") #endif #pragma comment(lib,"Ws2_32.lib") #endif
pengdao/simcc
simcc/json/json_cast.h
// Created: 2009/08/07 // Author: weizili #pragma once #include "simcc/inner_pre.h" #include "json_common.h" namespace simcc { namespace json { template<typename T > T* cast(json::Object* obj) { if (obj) { if (static_cast<JSONType>(T::Type) == obj->type()) { return static_cast<T*>(obj); } } return NULL; } template<typename T > const T* cast(const json::Object* obj) { if (obj) { if (static_cast<JSONType>(T::Type) == obj->type()) { return static_cast<const T*>(obj); } } return NULL; } template<typename T > T* cast(json::ObjectPtr& obj) { if (obj) { if (static_cast<JSONType>(T::Type) == obj->type()) { return static_cast<T*>(obj.get()); } } return NULL; } template<typename T > const T* cast(const json::ObjectPtr& obj) { if (obj) { if (static_cast<JSONType>(T::Type) == obj->type()) { return static_cast<const T*>(obj.get()); } } return NULL; } } }
pengdao/simcc
simcc/gcc_list.h
<reponame>pengdao/simcc #pragma once #include "simcc/platform_config.h" #include <list> namespace simcc { // A list with the same interface with std::list. // For gcc compiler, it has higher performance for list::size() #ifdef H_OS_WINDOWS template < typename T > class list : public std::list<T> {}; #else template < typename _Tp > class list : private std::list<_Tp > { typedef std::list<_Tp > BaseClass; size_t m_list_size; public: // type typedef typename BaseClass::allocator_type allocator_type; typedef typename BaseClass::const_iterator const_iterator; typedef typename BaseClass::const_pointer const_pointer; typedef typename BaseClass::const_reference const_reference; typedef typename BaseClass::const_reverse_iterator const_reverse_iterator; typedef typename BaseClass::difference_type difference_type; typedef typename BaseClass::iterator iterator; typedef typename BaseClass::pointer pointer; typedef typename BaseClass::reference reference; typedef typename BaseClass::reverse_iterator reverse_iterator; typedef typename BaseClass::size_type size_type; typedef typename BaseClass::value_type value_type; // member function using BaseClass::front; using BaseClass::back; using BaseClass::begin; using BaseClass::end; using BaseClass::empty; using BaseClass::rbegin; using BaseClass::rend; using BaseClass::get_allocator; using BaseClass::max_size; using BaseClass::reverse; using BaseClass::sort; public: /** * Erases all the elements. Note that this function only erases * the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ void clear() { m_list_size = 0; BaseClass::clear(); } /** * @brief Removes first element. * * This is a typical stack operation. It shrinks the %list by * one. Due to the nature of a %list this operation can be done * in constant time, and only invalidates iterators/references to * the element being removed. * * Note that no data is returned, and if the first element's data * is needed, it should be retrieved before pop_front() is * called. */ void pop_front() { erase(begin()); } /** * @brief Removes last element. * * This is a typical stack operation. It shrinks the %list by * one. Due to the nature of a %list this operation can be done * in constant time, and only invalidates iterators/references to * the element being removed. * * Note that no data is returned, and if the last element's data * is needed, it should be retrieved before pop_back() is called. */ void pop_back() { iterator __tmp = end(); erase(--__tmp); } /** * @brief Remove element at given position. * @param position Iterator pointing to element to be erased. * @return An iterator pointing to the next element (or end()). * * This function will erase the element at the given position and thus * shorten the %list by one. * * Due to the nature of a %list this operation can be done in * constant time, and only invalidates iterators/references to * the element being removed. The user is also cautioned that * this function only erases the element, and that if the element * is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibilty. */ iterator erase(iterator __position) { m_list_size --; return BaseClass::erase(__position); } /** * @brief Remove a range of elements. * @param first Iterator pointing to the first element to be erased. * @param last Iterator pointing to one past the last element to be * erased. * @return An iterator pointing to the element pointed to by @a last * prior to erasing (or end()). * * This function will erase the elements in the range @a * [first,last) and shorten the %list accordingly. * * Due to the nature of a %list this operation can be done in * constant time, and only invalidates iterators/references to * the element being removed. The user is also cautioned that * this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibilty. */ iterator erase(iterator __first, iterator __last) { while (__first != __last) { erase(__first++); } return __last; } void resize(size_type __new_size) { this->resize(__new_size, _Tp()); m_list_size = __new_size ; } /** * @brief Resizes the %list to the specified number of elements. * @param new_size Number of elements the %list should contain. * @param x Data with which new elements should be populated. * * This function will %resize the %list to the specified number * of elements. If the number is smaller than the %list's * current size the %list is truncated, otherwise the %list is * extended and new elements are populated with given data. */ void resize(size_type __new_size, const _Tp& __x) { iterator __i = begin(); size_type __len = 0; for (; __i != end() && __len < __new_size; ++__i, ++__len) ; if (__len == __new_size) { erase(__i, end()); } else { // __i == end() insert(end(), __new_size - __len, __x); } } /** * @brief Inserts given value into %list before specified iterator. * @param position An iterator into the %list. * @param x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before * the specified location. Due to the nature of a %list this * operation can be done in constant time, and does not * invalidate iterators and references. */ iterator insert(iterator __position, const _Tp& __x) { m_list_size++; return BaseClass::insert(__position , __x); } /** * @brief Inserts a number of copies of given data into the %list. * @param position An iterator into the %list. * @param n Number of elements to be inserted. * @param x Data to be inserted. * * This function will insert a specified number of copies of the * given data before the location specified by @a position. * * Due to the nature of a %list this operation can be done in * constant time, and does not invalidate iterators and * references. */ void insert(iterator __position, size_type __n, const value_type& __x) { m_list_size += __n; return BaseClass::insert(__position , __n , __x); } /** * @brief Inserts a range into the %list. * @param position An iterator into the %list. * @param first An input iterator. * @param last An input iterator. * * This function will insert copies of the data in the range [@a * first,@a last) into the %list before the location specified by * @a position. * * Due to the nature of a %list this operation can be done in * constant time, and does not invalidate iterators and * references. */ template <class _InputIterator> void insert(iterator __pos, _InputIterator __first, _InputIterator __last) { m_list_size += std::distance(__first , __last); BaseClass::insert(__pos , __first, __last); } /** Returns the number of elements in the %list. */ size_type size() const { return m_list_size; } /** * @brief Add data to the end of the %list. * @param x Data to be added. * * This is a typical stack operation. The function creates an * element at the end of the %list and assigns the given data to * it. Due to the nature of a %list this operation can be done * in constant time, and does not invalidate iterators and * references. */ void push_back(const _Tp& __x) { insert(end(), __x); } /** * @brief Add data to the front of the %list. * @param x Data to be added. * * This is a typical stack operation. The function creates an * element at the front of the %list and assigns the given data * to it. Due to the nature of a %list this operation can be * done in constant time, and does not invalidate iterators and * references. */ void push_front(const _Tp& __x) { insert(begin(), __x); } /** * @brief Remove all elements equal to value. * @param value The value to remove. * * Removes every element in the list equal to @a value. * Remaining elements stay in list order. Note that this * function only erases the elements, and that if the elements * themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibilty. */ void remove(const _Tp& value) { iterator __first = begin(); iterator __last = end(); while (__first != __last) { iterator __next = __first; ++__next; if (*__first == value) { erase(__first); } __first = __next; } } /** * @brief Remove consecutive duplicate elements. * * For each consecutive set of elements with the same value, * remove all but the first one. Remaining elements stay in * list order. Note that this function only erases the * elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibilty. */ void unique() { iterator __first = begin(); iterator __last = end(); if (__first == __last) { return; } iterator __next = __first; while (++__next != __last) { if (*__first == *__next) { erase(__next); } else { __first = __next; } __next = __first; } } /** * @brief Remove consecutive elements satisfying a predicate. * @param BinaryPredicate Binary predicate function or object. * * For each consecutive set of elements [first,last) that * satisfy predicate(first,i) where i is an iterator in * [first,last), remove all but the first one. Remaining * elements stay in list order. Note that this function only * erases the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibilty. */ template <class _BinaryPredicate> void unique(_BinaryPredicate __binary_pred) { iterator __first = begin(); iterator __last = end(); if (__first == __last) { return; } iterator __next = __first; while (++__next != __last) { if (__binary_pred(*__first, *__next)) { erase(__next); } else { __first = __next; } __next = __first; } } /** * @brief Remove all elements satisfying a predicate. * @param Predicate Unary predicate function or object. * * Removes every element in the list for which the predicate * returns true. Remaining elements stay in list order. Note * that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibilty. */ template <class _Predicate> void remove_if(_Predicate __pred) { iterator __first = begin(); iterator __last = end(); while (__first != __last) { iterator __next = __first; ++__next; if (__pred(*__first)) { erase(__first); } __first = __next; } } /** * @brief Assigns a given value to a %list. * @param n Number of elements to be assigned. * @param val Value to be assigned. * * This function fills a %list with @a n copies of the given * value. Note that the assignment completely changes the %list * and that the resulting %list's size is the same as the number * of elements assigned. Old data may be lost. */ void assign(size_type __n, const _Tp& __val) { iterator __i = begin(); for (; __i != end() && __n > 0; ++__i, --__n) { *__i = __val; } if (__n > 0) { insert(end(), __n, __val); } else { erase(__i, end()); } } /** * @brief Assigns a range to a %list. * @param first An input iterator. * @param last An input iterator. * * This function fills a %list with copies of the elements in the * range [@a first,@a last). * * Note that the assignment completely changes the %list and * that the resulting %list's size is the same as the number of * elements assigned. Old data may be lost. */ template <class _InputIterator> void assign(_InputIterator __first2, _InputIterator __last2) { iterator __first1 = begin(); iterator __last1 = end(); for (; __first1 != __last1 && __first2 != __last2; ++__first1, ++__first2) { *__first1 = *__first2; } if (__first2 == __last2) { erase(__first1, __last1); } else { insert(__last1, __first2, __last2); } } /** * @brief Swaps data with another %list. * @param x A %list of the same element and allocator types. * * This exchanges the elements between two lists in constant * time. Note that the global std::swap() function is * specialized such that std::swap(l1,l2) will feed to this * function. */ void swap(list<_Tp>& __x) { std::swap(m_list_size , __x.m_list_size); BaseClass::swap(__x); } /** * @brief Default constructor creates no elements. */ explicit list(const allocator_type& _Al = allocator_type()) : BaseClass(_Al) , m_list_size(0) { } /** * @brief Create a %list with copies of an exemplar element. * @param n The number of elements to initially create. * @param value An element to copy. * * This constructor fills the %list with @a n copies of @a value. */ list(size_type _Count, const _Tp& _Val, const allocator_type& _Al = allocator_type()) : BaseClass(_Count, _Val , _Al) , m_list_size(_Count) { } /** * @brief %list copy constructor. * @param x A %list of identical element and allocator types. * * The newly-created %list uses a copy of the allocation object used * by @a x. */ list(const list& __x) : BaseClass(__x.get_allocator()) , m_list_size(0) { this->insert(begin(), __x.begin(), __x.end()); } /** * @brief Builds a %list from a range. * @param first An input iterator. * @param last An input iterator. * * Create a %list consisting of copies of the elements from * [@a first,@a last). This is linear in N (where N is * distance(@a first,@a last)). * * @if maint * We don't need any dispatching tricks here, because insert does all of * that anyway. * @endif */ template<class InputIterator > list(InputIterator _First, InputIterator _Last, const allocator_type& _Al = allocator_type()) : m_list_size(0) , BaseClass(_Al) { this->insert(begin(), _First, _Last); } /** * @brief %list assignment operator. * @param x A %list of identical element and allocator types. * * All the elements of @a x are copied, but unlike the copy * constructor, the allocator object is not copied. */ list& operator=(const list& __x) { assign(__x.begin() , __x.end()); return *this; } /** * @brief Insert contents of another %list. * @param position Iterator referencing the element to insert before. * @param x Source list. * * The elements of @a x are inserted in constant time in front of * the element referenced by @a position. @a x becomes an empty * list. */ void splice(iterator __position, list& __x) { if (!__x.empty()) { this->m_list_size += __x.size(); __x.m_list_size = 0; BaseClass::splice(__position , __x); } } /** * @brief Insert element from another %list. * @param position Iterator referencing the element to insert before. * @param x Source list. * @param i Iterator referencing the element to move. * * Removes the element in list @a x referenced by @a i and * inserts it into the current list before @a position. */ void splice(iterator __position, list& __x, iterator __i) { if (__i == __x.end()) { return; } this->m_list_size++; __x.m_list_size--; BaseClass::splice(__position , __x , __i); } /** * @brief Insert range from another %list. * @param position Iterator referencing the element to insert before. * @param x Source list. * @param first Iterator referencing the start of range in x. * @param last Iterator referencing the end of range in x. * * Removes elements in the range [first,last) and inserts them * before @a position in constant time. * * Undefined if @a position is in [first,last). */ void splice(iterator __position, list& __x , iterator __first, iterator __last) { if (__first != __last) { const difference_type nSize = distance(__first , __last); this->m_list_size += nSize; __x.m_list_size -= nSize; BaseClass::splice(__position , __x , __first , __last); } } }; #endif }
pengdao/simcc
simcc/json/json_tokener.h
<reponame>pengdao/simcc // Created: 2009/08/07 // Author: weizili #pragma once #include "simcc/tokener.h" #include "json.h" namespace simcc { namespace json { class Object; // A JSONTokener takes a source string and extracts characters and tokens from // it. It is used by the JSONObject and JSONArray constructors to parse // JSON source strings. class JSONTokener : public simcc::Tokener { public: // Construct a JSONTokener from a string. You can use this token to // build a JSONObject // // @param ps A source string. // @param ps_len The length of the source string // if it equals -1, we will use strlen(ps) to calculate the length. JSONTokener(const string& s); JSONTokener(const char* ps, const simcc::int32 ps_len = -1); ~JSONTokener(); // Get the characters up to the next close quote character. // Backslash processing is done. The formal JSON format does not // allow strings in single quotes, but an implementation is allowed to // accept them. // @param quote The quoting character, either // <code>"</code>(simcc::f64 quote) or // <code>'</code>(single quote). // @param rs the string we needed // @return true, if no error happened // false, if Unterminated string. bool NextString(char quote, string& rs); bool NextString(char quote, bool parse_protobuf, string& rs); // Get the next value. The value can be a Boolean, Double, Integer, // JSONArray, JSONObject, Long, or string, or the JSONObject.NULL object. // @return An object. or NULL if something wrong Object* NextValue(JSONParser* parser); // @brief skip comment strings // Skip c-style or cpp-style comment // @note when return false, we don't skip any character // @return true, if skip successfully // false, if the comment format is wrong. bool SkipComment(); bool SkipCStyleComment(); /* this is a c-style comment*/ bool SkipCppStyleComment(); // this is a cpp-style comment template<typename _stream> bool ConvertUnicodeToUTF8(simcc::uint32 unicode, _stream& stream); // Convert an unicode escape string sequence to an unicode number bool DecodeUnicodeEscapeSequence(simcc::uint32& unicode); // Convert an unicode number to UTF8 string static string ConvertUnicodeToUTF8(simcc::uint32 unicode); // Convert an unicode number to an unicode escape string sequence. e.g: 0x8912 --> "\\u8912" static void EncodeUnicodeNumber(simcc::uint32 codepoint, simcc::DataStream& stream); static void EncodeUnicodeNumber(simcc::uint32 codepoint, char encbuf[/*12*/], simcc::uint32& encbuf_len); private: // Convert an unicode 4 bytes escape string sequence to an unicode number bool DecodeUnicode4BytesSequence(simcc::uint32& unicode); private: enum { kDefaultBufferSize = 512 }; simcc::DataStream buf_; // The data cache buffer to improve performance }; inline JSONTokener::JSONTokener(const string& s) : Tokener(s) , buf_(kDefaultBufferSize) { } inline JSONTokener::JSONTokener(const char* ps, const simcc::int32 len) : Tokener(ps, len) , buf_(kDefaultBufferSize) { } inline JSONTokener::~JSONTokener() { } inline bool JSONTokener::NextString(char quote, bool parse_protobuf, string& rs) { buf_.Reset(); #define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 static const char escape[256] = { Z16, Z16, 0, 0, '\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '/', Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '\\', 0, 0, 0, 0, 0, '\b', 0, 0, 0, '\f', 0, 0, 0, 0, 0, 0, 0, '\n', 0, 0, 0, '\r', 0, '\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 }; #undef Z16 char c = 0; for (;;) { c = Next(); switch (c) { case 0: //fprintf( stderr, "Unterminated string\n" ); return false; case '\\': // Escape character c = Next(); #if 1 if (escape[(unsigned char)c]) { buf_.Write(escape[(unsigned char)c]); } else if (c == 'u') { // e.g. \u1524 is a unicode character simcc::uint32 unicode = 0; if (!DecodeUnicodeEscapeSequence(unicode)) { //fprintf( stderr, "Illegal unicode escape.\n" ); return false; } if (!JSONTokener::ConvertUnicodeToUTF8(unicode, buf_)) { //fprintf( stderr, "Illegal escape unicode [%c]\n", c ); return false; } } else { if (parse_protobuf) { //TODO convert "\346\226\260\346\265\252\347\275\221" to a utf8 string buf_.Write('\\'); buf_.Write(c); } else { //fprintf( stderr, "Illegal escape.[%c]\n", c ); return false; } } #else switch (c) { case '"': buf_ << c; break; case '\'': buf_ << c; break; case '/': buf_ << c; break; case '\\': buf_ << c; break; case 'b': buf_ << '\b'; break; case 'f': buf_ << '\f'; break; case 'n': buf_ << '\n'; break; case 'r': buf_ << '\r'; break; case 't': buf_ << '\t'; break; case 'u': { // e.g. \u1524 is a unicode character simcc::uint32 unicode = 0; if (!DecodeUnicodeEscapeSequence(unicode)) { //fprintf( stderr, "Illegal unicode escape.\n" ); return false; } if (!JSONTokener::ConvertUnicodeToUTF8(unicode, buf_)) { return false; } } break; default: //fprintf( stderr, "Illegal escape.[%c]\n", c ); return false; } #endif break; default: if (c == quote) { rs.assign(buf_.data(), buf_.size()); return true; } buf_.Write(c); break; } } // end of for ( ;; ) } inline bool JSONTokener::NextString(char quote, string& rs) { return NextString(quote, false, rs); } inline Object* JSONTokener::NextValue(JSONParser* parser) { if (!SkipComment()) { //printf("wrong format of comment"); parser->set_error(JSONParser::kCommentFormatError, this); return 0; } char c = NextClean(); switch (c) { case '"': case '\'': { JSONString* jstring = new JSONString(); if (!NextString(c, jstring->value())) { delete jstring; jstring = NULL; parser->set_error(JSONParser::kJSONStringNotQuoted, this->GetCurrentPosition()); } return jstring; } case '{': Back(); { JSONObject* jobj = new JSONObject(); if (jobj->Parse(this) > 0 && jobj->error() == JSONParser::kNoError) { return jobj; } else { parser->set_error(jobj->error(), this->GetCurrentPosition()); delete jobj; return NULL; } } case '[': case '(': Back(); { JSONArray* jarray = new JSONArray(); if (jarray->Parse(this) > 0 && jarray->error() == JSONParser::kNoError) { return jarray; } else { parser->set_error(jarray->error(), this); delete jarray; return NULL; } } default: //Handle unquoted text like: true, false, or null, or it can be a number. break; } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ //the static table of ",:]}/\\\"[{;=#" and space, tab and control characters static char specialchars[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; const char* startpos = GetCurrent() - 1; while (specialchars[(int)c]) { c = Next(); } Back(); if (GetCurrent() <= startpos) { //printf( "Miss value\n" ); parser->set_error(JSONParser::kBlankValue, this); return NULL; } return JSONObject::ConvertToObject(startpos, GetCurrent() - startpos, parser, this); } inline bool JSONTokener::SkipComment() { char c = NextClean(); if (c != '/') { Back(); return true; } c = Next(); bool successful = false; if (c == '*') { successful = SkipCStyleComment(); } else if (c == '/') { successful = SkipCppStyleComment(); } if (successful) { return SkipComment(); } else { Back(); return false; } } inline bool JSONTokener::SkipCStyleComment() { const char* iCurrentPos = GetCurrent(); while (!IsEnd()) { if (Next() == '*' && Current() == '/') { Next();//skip '/' return true; } } SetCurrent(iCurrentPos); return false; } inline bool JSONTokener::SkipCppStyleComment() { const char* iCurrentPos = GetCurrent(); { if (SkipToNextLine()) { return true; } } SetCurrent(iCurrentPos); return false; } inline string JSONTokener::ConvertUnicodeToUTF8(simcc::uint32 unicode) { string result; // based on description from http://en.wikipedia.org/wiki/UTF-8 if (unicode <= 0x7f) { result.resize(1); result[0] = static_cast<char>(unicode); } else if (unicode <= 0x7FF) { result.resize(2); result[1] = static_cast<char>(0x80 | (0x3f & unicode)); result[0] = static_cast<char>(0xC0 | (0x1f & (unicode >> 6))); } else if (unicode <= 0xFFFF) { result.resize(3); result[2] = static_cast<char>(0x80 | (0x3f & unicode)); result[1] = 0x80 | static_cast<char>((0x3f & (unicode >> 6))); result[0] = 0xE0 | static_cast<char>((0xf & (unicode >> 12))); } else if (unicode <= 0x10FFFF) { result.resize(4); result[3] = static_cast<char>(0x80 | (0x3f & unicode)); result[2] = static_cast<char>(0x80 | (0x3f & (unicode >> 6))); result[1] = static_cast<char>(0x80 | (0x3f & (unicode >> 12))); result[0] = static_cast<char>(0xF0 | (0x7 & (unicode >> 18))); } return result; } template<typename _stream> inline bool JSONTokener::ConvertUnicodeToUTF8(simcc::uint32 unicode, _stream& stream) { // based on description from http://en.wikipedia.org/wiki/UTF-8 if (unicode <= 0x7f) { // stream.resize( 1 ); // stream[0] = static_cast<char>( unicode ); stream.put(static_cast<char>(unicode)); } else if (unicode <= 0x7FF) { // stream.resize( 2 ); // stream[1] = static_cast<char>( 0x80 | ( 0x3f & unicode ) ); // stream[0] = static_cast<char>( 0xC0 | ( 0x1f & ( unicode >> 6 ) ) ); stream.put(0xC0 | ((unicode >> 6) & 0xFF)); stream.put(0x80 | ((unicode & 0x3F))); } else if (unicode <= 0xFFFF) { stream.put(0xE0 | ((unicode >> 12) & 0xFF)); stream.put(0x80 | ((unicode >> 6) & 0x3F)); stream.put(0x80 | (unicode & 0x3F)); // stream.resize( 3 ); // stream[2] = static_cast<char>( 0x80 | ( 0x3f & unicode ) ); // stream[1] = 0x80 | static_cast<char>( ( 0x3f & ( unicode >> 6 ) ) ); // stream[0] = 0xE0 | static_cast<char>( ( 0xf & ( unicode >> 12 ) ) ); } else if (unicode <= 0x10FFFF) { stream.put(0xF0 | ((unicode >> 18) & 0xFF)); stream.put(0x80 | ((unicode >> 12) & 0x3F)); stream.put(0x80 | ((unicode >> 6) & 0x3F)); stream.put(0x80 | (unicode & 0x3F)); // stream.resize( 4 ); // stream[3] = static_cast<char>( 0x80 | ( 0x3f & unicode ) ); // stream[2] = static_cast<char>( 0x80 | ( 0x3f & ( unicode >> 6 ) ) ); // stream[1] = static_cast<char>( 0x80 | ( 0x3f & ( unicode >> 12 ) ) ); // stream[0] = static_cast<char>( 0xF0 | ( 0x7 & ( unicode >> 18 ) ) ); } else { return false; } return true; } inline bool JSONTokener::DecodeUnicodeEscapeSequence(simcc::uint32& unicode) { if (!DecodeUnicode4BytesSequence(unicode)) { return false; } if (unicode >= 0xD800 && unicode <= 0xDBFF) { // surrogate pairs if (GetReadableSize() < 6) { return false; } unsigned int surrogatePair; if (Next() == '\\' && Next() == 'u') { if (DecodeUnicode4BytesSequence(surrogatePair)) { unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); } else { return false; } } else { return false; } } return true; } inline bool JSONTokener::DecodeUnicode4BytesSequence(simcc::uint32& unicode) { enum { Unicode_Len = 4 };// an unicode has 4 bytes if (GetReadableSize() < Unicode_Len) { return false; } unicode = 0; for (int index = 0; index < Unicode_Len; ++index) { char c = Next(); unicode = unicode << 4; if (c >= '0' && c <= '9') { unicode += c - '0'; } else if (c >= 'a' && c <= 'f') { unicode += c - 'a' + 10; } else if (c >= 'A' && c <= 'F') { unicode += c - 'A' + 10; } else { return false; } } return true; } inline void JSONTokener::EncodeUnicodeNumber(simcc::uint32 codepoint, char encbuf[/*12*/], simcc::uint32& encbuf_len) { char* begin = (char*)encbuf; // codepoint is in BMP if (codepoint < 0x10000) { begin[0] = '\\'; begin[1] = 'u'; //uint16-t high byte char _0h = ((codepoint & 0xF000) >> 12); if (_0h <= 9) { begin[2] = _0h + '0'; } else { begin[2] = _0h + 'a' - 10; } char _0l = ((codepoint & 0x0F00) >> 8); if (_0l <= 9) { begin[3] = _0l + '0'; } else { begin[3] = _0l + 'a' - 10; } //uint16-t low byte char _1h = ((codepoint & 0xF0) >> 4); if (_1h <= 9) { begin[4] = _1h + '0'; } else { begin[4] = _1h + 'a' - 10; } char _1l = (codepoint & 0x0F); if (_1l <= 9) { begin[5] = _1l + '0'; } else { begin[5] = _1l + 'a' - 10; } encbuf_len = 6; } else { // not in BMP -> construct a UTF-16 surrogate pair codepoint -= 0x10000; int32_t first = 0xD800 | ((codepoint & 0xffc00) >> 10); int32_t last = 0xDC00 | (codepoint & 0x003ff); //Write First { begin[0] = '\\'; begin[1] = 'u'; //uint16-t high byte char _0h = ((first & 0xF000) >> 12); if (_0h <= 9) { begin[2] = _0h + '0'; } else { begin[2] = _0h + 'a' - 10; } char _0l = ((first & 0x0F00) >> 8); if (_0l <= 9) { begin[3] = _0l + '0'; } else { begin[3] = _0l + 'a' - 10; } //uint16-t low byte char _1h = ((first & 0xF0) >> 4); if (_1h <= 9) { begin[4] = _1h + '0'; } else { begin[4] = _1h + 'a' - 10; } char _1l = (first & 0x0F); if (_1l <= 9) { begin[5] = _1l + '0'; } else { begin[5] = _1l + 'a' - 10; } } //Write last { begin[6] = '\\'; begin[7] = 'u'; //uint16-t high byte char _0h = ((last & 0xF000) >> 12); if (_0h <= 9) { begin[8] = _0h + '0'; } else { begin[8] = _0h + 'a' - 10; } char _0l = ((last & 0x0F00) >> 8); if (_0l <= 9) { begin[9] = _0l + '0'; } else { begin[9] = _0l + 'a' - 10; } //uint16-t low byte char _1h = ((last & 0xF0) >> 4); if (_1h <= 9) { begin[10] = _1h + '0'; } else { begin[10] = _1h + 'a' - 10; } char _1l = (last & 0x0F); if (_1l <= 9) { begin[11] = _1l + '0'; } else { begin[11] = _1l + 'a' - 10; } } encbuf_len = (12); } } inline void JSONTokener::EncodeUnicodeNumber(simcc::uint32 codepoint, simcc::DataStream& stream) { //Ensure there is enough memory to hold the data stream.Expand(12); char* begin = (char*)stream.GetCurrentWriteBuffer(); // codepoint is in BMP if (codepoint < 0x10000) { begin[0] = '\\'; begin[1] = 'u'; //uint16-t high byte char _0h = ((codepoint & 0xF000) >> 12); if (_0h <= 9) { begin[2] = _0h + '0'; } else { begin[2] = _0h + 'a' - 10; } char _0l = ((codepoint & 0x0F00) >> 8); if (_0l <= 9) { begin[3] = _0l + '0'; } else { begin[3] = _0l + 'a' - 10; } //uint16-t low byte char _1h = ((codepoint & 0xF0) >> 4); if (_1h <= 9) { begin[4] = _1h + '0'; } else { begin[4] = _1h + 'a' - 10; } char _1l = (codepoint & 0x0F); if (_1l <= 9) { begin[5] = _1l + '0'; } else { begin[5] = _1l + 'a' - 10; } stream.seekp(6); } else { // not in BMP -> construct a UTF-16 surrogate pair codepoint -= 0x10000; int32_t first = 0xD800 | ((codepoint & 0xffc00) >> 10); int32_t last = 0xDC00 | (codepoint & 0x003ff); //Write First { begin[0] = '\\'; begin[1] = 'u'; //uint16-t high byte char _0h = ((first & 0xF000) >> 12); if (_0h <= 9) { begin[2] = _0h + '0'; } else { begin[2] = _0h + 'a' - 10; } char _0l = ((first & 0x0F00) >> 8); if (_0l <= 9) { begin[3] = _0l + '0'; } else { begin[3] = _0l + 'a' - 10; } //uint16-t low byte char _1h = ((first & 0xF0) >> 4); if (_1h <= 9) { begin[4] = _1h + '0'; } else { begin[4] = _1h + 'a' - 10; } char _1l = (first & 0x0F); if (_1l <= 9) { begin[5] = _1l + '0'; } else { begin[5] = _1l + 'a' - 10; } } //Write last { begin[6] = '\\'; begin[7] = 'u'; //uint16-t high byte char _0h = ((last & 0xF000) >> 12); if (_0h <= 9) { begin[8] = _0h + '0'; } else { begin[8] = _0h + 'a' - 10; } char _0l = ((last & 0x0F00) >> 8); if (_0l <= 9) { begin[9] = _0l + '0'; } else { begin[9] = _0l + 'a' - 10; } //uint16-t low byte char _1h = ((last & 0xF0) >> 4); if (_1h <= 9) { begin[10] = _1h + '0'; } else { begin[10] = _1h + 'a' - 10; } char _1l = (last & 0x0F); if (_1l <= 9) { begin[11] = _1l + '0'; } else { begin[11] = _1l + 'a' - 10; } } stream.seekp(12); } } } }