repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
tailhook/paperjam
src/print.h
<gh_stars>1-10 #ifndef _H_PRINT #define _H_PRINT void print_message(char *data, size_t datalen, int more); #endif // _H_PRINT
xackery/eqgzi
src/util.h
<filename>src/util.h #ifndef UTIL_H #define UTIL_H #include "types.h" #include "geo.h" #include <cstdio> #include <cstring> #include <unordered_map> #include <lua.hpp> namespace Util { void LoadFunctions(lua_State* L); class Buffer; byte* CheckHeader(lua_State* L, const char* magic, const char* err_name); void PrepareWrite(lua_State* L, const char* err_name); int FinishWrite(lua_State* L, Buffer& buf); double FloatToDouble(float val); uint32 GetInt(lua_State* L, int index, const char* name); uint32 GetInt(lua_State* L, int index, int pos); float GetFloat(lua_State* L, int index, const char* name); const char* GetString(lua_State* L, int index, const char* name, uint32& len); const char* GetString(lua_State* L, int index, const char* name); void WriteGeometry(lua_State* L, Buffer& data_buf, Buffer& name_buf, uint32& mat_count, uint32& vert_count, uint32& tri_count); class Buffer { public: Buffer(); void Add(const void* in_data, uint32 len); byte* Take(); uint32 GetLen() { return mLen; } private: uint32 mLen; uint32 mCap; byte* mData; }; typedef std::unordered_map<const char*, uint32> FoundNamesMap; uint32 AddName(lua_State* L, const char* id, Buffer& name_buf, FoundNamesMap& found_names); } #endif//UTIL_H
xackery/eqgzi
include/iup/iup_scintilla.h
<reponame>xackery/eqgzi /** \file * \brief Scintilla control. * * See Copyright Notice in "iup.h" */ #ifndef __IUP_SCINTILLA_H #define __IUP_SCINTILLA_H #ifdef __cplusplus extern "C" { #endif void IupScintillaOpen(void); Ihandle *IupScintilla(void); #ifdef __cplusplus } #endif #endif
xackery/eqgzi
src/viewer.h
#include <cstdio> #include <cstring> #include <thread> #include <atomic> #include <chrono> #include <unordered_map> #include <lua.hpp> #include <irrlicht.h> #include <FreeImagePlus.h> #include "types.h" #include "util.h" #include <cmath> using namespace irr; namespace Viewer { void LoadFunctions(lua_State* L); class CameraController : public IEventReceiver { public: CameraController() : mMovespeed(150.0f), mMoveDirection(MOVE_NONE), mTurnDirection(TURN_NONE), mHasMoved(true), mMouseDown(false), mRelX(0), mRelY(0) { } bool CheckMoved() { if (mHasMoved) { mHasMoved = false; return true; } return false; } void ApplyMovement(float delta); void SetPtrs(IrrlichtDevice* device, scene::ICameraSceneNode* camera) { mDevice = device; mCamera = camera; } virtual bool OnEvent(const SEvent& ev) override; bool HandleKeyboardInput(const SEvent::SKeyInput& ev); bool HandleMouseInput(const SEvent::SMouseInput& ev); private: float mMovespeed; int8 mMoveDirection; int8 mTurnDirection; IrrlichtDevice* mDevice; scene::ICameraSceneNode* mCamera; bool mHasMoved; bool mMouseDown; float mMouseX; float mMouseY; float mRelX; float mRelY; enum Movement { MOVE_FORWARD = -1, MOVE_NONE, MOVE_BACKWARD }; enum Turn { TURN_LEFT = -1, TURN_NONE, TURN_RIGHT }; }; class ImageFile : public io::IReadFile { public: ImageFile(const char* name, byte* data, uint32 len) : mName(name), mData(data), mLength(len), mPos(0) { } ~ImageFile() { if (mData) delete[] mData; } virtual const io::path& getFileName() const { return mName; } virtual long getPos() const { return mPos; } virtual long getSize() const { return mLength; } virtual int32 read(void* buffer, uint32 sizeToRead) { long read = mPos + sizeToRead; if (read >= mLength) sizeToRead = mLength - mPos; memcpy(buffer, &mData[mPos], sizeToRead); mPos = read; return sizeToRead; } virtual bool seek(long finalPos, bool relativeMovement = false) { if (relativeMovement) finalPos += mPos; if (finalPos >= mLength) return false; mPos = finalPos; return true; } private: irr::io::path mName; byte* mData; long mLength; long mPos; }; }
xackery/eqgzi
include/iup/iupcontrols.h
<filename>include/iup/iupcontrols.h<gh_stars>0 /** \file * \brief initializes dial, gauge, colorbrowser, colorbar controls. * * See Copyright Notice in "iup.h" */ #ifndef __IUPCONTROLS_H #define __IUPCONTROLS_H #ifdef __cplusplus extern "C" { #endif int IupControlsOpen(void); void IupControlsClose(void); /* for backward compatibility only, does nothing since IUP 3. DEPRECATED. It will be removed in a future version. */ Ihandle* IupColorbar(void); Ihandle* IupCells(void); Ihandle *IupColorBrowser(void); Ihandle *IupColorBrowser(void); Ihandle *IupGauge(void); Ihandle *IupDial(const char* type); Ihandle* IupMatrix(const char *action); Ihandle* IupMatrixList(void); /* IupMatrix utilities (DEPRECATED, use IupSetAttributeId2 functions). It will be removed in a future version. */ void IupMatSetAttribute (Ihandle* ih, const char* name, int lin, int col, const char* value); void IupMatStoreAttribute(Ihandle* ih, const char* name, int lin, int col, const char* value); char* IupMatGetAttribute (Ihandle* ih, const char* name, int lin, int col); int IupMatGetInt (Ihandle* ih, const char* name, int lin, int col); float IupMatGetFloat (Ihandle* ih, const char* name, int lin, int col); void IupMatSetfAttribute (Ihandle* ih, const char* name, int lin, int col, const char* format, ...); /* Used by IupColorbar */ #define IUP_PRIMARY -1 #define IUP_SECONDARY -2 #ifdef __cplusplus } #endif #endif
xackery/eqgzi
src/geo.h
#ifndef GEO_H #define GEO_H #include "types.h" struct Material { uint32 index; uint32 name_index; uint32 shader_index; uint32 property_count; static const uint32 SIZE = sizeof(uint32) * 4; }; struct Property { uint32 name_index; uint32 type; union { uint32 i; float f; } value; static const uint32 SIZE = sizeof(uint32) * 3; }; struct Vertex { float x, y, z; float i, j, k; float u, v; static const uint32 SIZE = sizeof(float) * 8; }; struct VertexV3 { float x, y, z; float i, j, k; uint32 color; float unknown[2]; float u, v; static const uint32 SIZE = sizeof(float) * 11; }; struct Triangle { uint32 index[3]; int material; uint32 flag; static const uint32 SIZE = sizeof(uint32) * 5; }; #endif
xackery/eqgzi
src/ter.h
<gh_stars>0 #include <lua.hpp> #include <cstdio> #include <cstring> #include "types.h" #include "util.h" #include "geo.h" namespace TER { void LoadFunctions(lua_State* L); struct Header { char magic[4]; //EQGT uint32 version; uint32 strings_len; uint32 material_count; uint32 vertex_count; uint32 triangle_count; static const uint32 SIZE = sizeof(uint32) * 6; }; }
xackery/eqgzi
src/wld.h
#include <lua.hpp> #include <cstdio> #include <cstring> #include <vector> #include <unordered_map> #include <unordered_set> #include <string> #include "types.h" #include "util.h" namespace WLD { void LoadFunctions(lua_State* L); struct Header { char magic[4]; uint32 version; uint32 frag_count; uint32 unknownA[2]; uint32 strings_len; uint32 unknownB; static const uint32 SIZE = sizeof(uint32) * 7; static const uint32 VERSION1 = 0x00015500; static const uint32 VERSION2 = 0x1000C800; }; struct FragHeader { uint32 len; uint32 type; static const uint32 SIZE = sizeof(uint32) * 2; }; struct MeshFrag { int nameref; uint32 flag; int texture_list_ref; int anim_vert_ref; uint32 unknownA[2]; float x, y, z; float rotation[3]; float unusedA[7]; uint16 vert_count; uint16 uv_count; uint16 normal_count; uint16 color_count; uint16 poly_count; uint16 vert_piece_count; uint16 poly_texture_count; uint16 vert_texture_count; uint16 size9; uint16 scale; static const uint32 SIZE = sizeof(uint16) * 10 + sizeof(uint32) * 19; }; struct RawVertex { int16 x, y, z; static const uint32 SIZE = sizeof(int16) * 3; }; struct RawUV16 { int16 u, v; static const uint32 SIZE = sizeof(int16) * 2; }; struct RawUV32 { int32 u, v; static const uint32 SIZE = sizeof(int32) * 2; }; struct RawNormal { int8 i, j, k; static const uint32 SIZE = sizeof(int8) * 3; }; struct RawTriangle { uint16 flag; uint16 index[3]; static const uint32 SIZE = sizeof(uint16) * 4; }; struct RawTextureEntry { uint16 count; uint16 index; static const uint32 SIZE = sizeof(uint16) * 2; }; struct Frag31 { FragHeader header; int nameref; uint32 flag; uint32 ref_count; static const uint32 SIZE = FragHeader::SIZE + sizeof(uint32) * 3; }; struct Frag30 { FragHeader header; int nameref; uint32 flag; uint32 visibility_flag; uint32 unknown[3]; int ref; }; struct Frag05 { FragHeader header; int nameref; int ref; uint32 flag; }; struct Frag04 { FragHeader header; int nameref; uint32 flag; int count; //uint32 unknown[2]; int ref; //ignoring additional refs (animated textures) //static const uint32 SIZE = FragHeader::SIZE + sizeof(uint32) * 5; }; struct Frag03 { FragHeader header; int nameref; int count; uint16 len; byte string[2]; }; }
xackery/eqgzi
src/zon.h
<gh_stars>0 #include <lua.hpp> #include <cstdio> #include <cstring> #include "types.h" #include "util.h" namespace ZON { void LoadFunctions(lua_State* L); struct Header { char magic[4]; //EQGZ uint32 version; uint32 strings_len; uint32 model_count; uint32 object_count; uint32 region_count; uint32 light_count; static const uint32 SIZE = sizeof(uint32) * 7; }; struct Model { uint32 name_index; static const uint32 SIZE = sizeof(uint32); }; struct Object //"placeable" { int id; uint32 name_index; float x, y, z; float rotation_x, rotation_y, rotation_z; float scale; static const uint32 SIZE = sizeof(uint32) * 9; }; struct Region { uint32 name_index; float center_x, center_y, center_z; float unknownA; uint32 unknownB, unknownC; float extent_x, extent_y, extent_z; static const uint32 SIZE = sizeof(uint32) * 10; }; struct Light { uint32 name_index; float x, y, z; float r, b, g; float radius; static const uint32 SIZE = sizeof(float) * 8; }; }
xackery/eqgzi
src/types.h
#ifndef TYPES_H #define TYPES_H #include <cstdint> #include <cstdlib> typedef std::uint8_t byte; typedef std::uint8_t uint8; typedef std::int8_t int8; typedef std::uint16_t uint16; typedef std::int16_t int16; typedef std::uint32_t uint32; typedef std::int32_t int32; typedef std::uint64_t uint64; typedef std::int64_t int64; //#ifdef _WIN32 //#define snprintf _snprintf //#endif #endif//TYPES_H
xackery/eqgzi
include/iup/iup_mglplot.h
<gh_stars>10-100 /** \file * \brief Plot component for Iup. * * See Copyright Notice in "iup.h" */ #ifndef __IUP_MGLPLOT_H #define __IUP_MGLPLOT_H #ifdef __cplusplus extern "C" { #endif /* Initialize IupMglPlot widget class */ void IupMglPlotOpen(void); /* Create an IupMglPlot widget instance */ Ihandle* IupMglPlot(void); /***********************************************/ /* Additional API */ void IupMglPlotBegin(Ihandle *ih, int dim); void IupMglPlotAdd1D(Ihandle *ih, const char* name, float y); void IupMglPlotAdd2D(Ihandle *ih, float x, float y); void IupMglPlotAdd3D(Ihandle *ih, float x, float y, float z); int IupMglPlotEnd(Ihandle *ih); int IupMglPlotNewDataSet(Ihandle *ih, int dim); void IupMglPlotInsert1D(Ihandle* ih, int ds_index, int sample_index, const char** names, const float* y, int count); void IupMglPlotInsert2D(Ihandle* ih, int ds_index, int sample_index, const float* x, const float* y, int count); void IupMglPlotInsert3D(Ihandle* ih, int ds_index, int sample_index, const float* x, const float* y, const float* z, int count); void IupMglPlotSet1D(Ihandle* ih, int ds_index, const char** names, const float* y, int count); void IupMglPlotSet2D(Ihandle* ih, int ds_index, const float* x, const float* y, int count); void IupMglPlotSet3D(Ihandle* ih, int ds_index, const float* x, const float* y, const float* z, int count); void IupMglPlotSetFormula(Ihandle* ih, int ds_index, const char* formulaX, const char* formulaY, const char* formulaZ, int count); void IupMglPlotSetData(Ihandle* ih, int ds_index, const float* data, int count_x, int count_y, int count_z); void IupMglPlotLoadData(Ihandle* ih, int ds_index, const char* filename, int count_x, int count_y, int count_z); void IupMglPlotSetFromFormula(Ihandle* ih, int ds_index, const char* formula, int count_x, int count_y, int count_z); void IupMglPlotTransform(Ihandle* ih, float x, float y, float z, int *ix, int *iy); void IupMglPlotTransformXYZ(Ihandle* ih, int ix, int iy, float *x, float *y, float *z); void IupMglPlotDrawMark(Ihandle* ih, float x, float y, float z); void IupMglPlotDrawLine(Ihandle* ih, float x1, float y1, float z1, float x2, float y2, float z2); void IupMglPlotDrawText(Ihandle* ih, const char* text, float x, float y, float z); void IupMglPlotPaintTo(Ihandle *ih, const char* format, int w, int h, float dpi, void *data); /***********************************************/ #ifdef __cplusplus } #endif #endif
xackery/eqgzi
src/mod.h
#include <lua.hpp> #include <cstdio> #include <cstring> #include "types.h" #include "util.h" #include "geo.h" namespace MOD { void LoadFunctions(lua_State* L); struct Header { char magic[4]; //EQGM uint32 version; uint32 strings_len; uint32 material_count; uint32 vertex_count; uint32 triangle_count; uint32 bone_count; static const uint32 SIZE = sizeof(uint32) * 7; //in case of 64bit alignment }; struct Bone { uint32 name_index; float unknown[13]; static const uint32 SIZE = sizeof(float) * 14; }; struct BoneAssignment //not 100% that's what this is, but it would make sense { uint32 unknown[9]; static const uint32 SIZE = sizeof(uint32) * 9; }; }
jjbourdev/IGListKit
Examples/Examples-iOS/Pods/Target Support Files/Pods-IGListKitTodayExample/Pods-IGListKitTodayExample-umbrella.h
<filename>Examples/Examples-iOS/Pods/Target Support Files/Pods-IGListKitTodayExample/Pods-IGListKitTodayExample-umbrella.h /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double Pods_IGListKitTodayExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_IGListKitTodayExampleVersionString[];
jjbourdev/IGListKit
Examples/Examples-tvOS/Pods/Target Support Files/IGListKit/IGListKit-umbrella.h
<filename>Examples/Examples-tvOS/Pods/Target Support Files/IGListKit/IGListKit-umbrella.h /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "IGListAdapter.h" #import "IGListAdapterDataSource.h" #import "IGListAdapterDelegate.h" #import "IGListAdapterMoveDelegate.h" #import "IGListAdapterPerformanceDelegate.h" #import "IGListAdapterUpdateListener.h" #import "IGListAdapterUpdater.h" #import "IGListAdapterUpdaterDelegate.h" #import "IGListBatchContext.h" #import "IGListBindable.h" #import "IGListBindingSectionController.h" #import "IGListBindingSectionControllerDataSource.h" #import "IGListBindingSectionControllerSelectionDelegate.h" #import "IGListCollectionContext.h" #import "IGListCollectionScrollingTraits.h" #import "IGListCollectionView.h" #import "IGListCollectionViewDelegateLayout.h" #import "IGListCollectionViewLayout.h" #import "IGListCollectionViewLayoutCompatible.h" #import "IGListDisplayDelegate.h" #import "IGListGenericSectionController.h" #import "IGListKit.h" #import "IGListReloadDataUpdater.h" #import "IGListScrollDelegate.h" #import "IGListSectionController.h" #import "IGListSingleSectionController.h" #import "IGListSupplementaryViewSource.h" #import "IGListTransitionDelegate.h" #import "IGListUpdatingDelegate.h" #import "IGListWorkingRangeDelegate.h" FOUNDATION_EXPORT double IGListKitVersionNumber; FOUNDATION_EXPORT const unsigned char IGListKitVersionString[];
jjbourdev/IGListKit
Source/IGListKit/IGListAdapterUpdaterDelegate.h
<reponame>jjbourdev/IGListKit /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import <UIKit/UIKit.h> #import <IGListDiffKit/IGListBatchUpdateData.h> @class IGListAdapterUpdater; @class IGListIndexSetResult; @protocol IGListDiffable; NS_ASSUME_NONNULL_BEGIN /** A protocol that receives events about `IGListAdapterUpdater` operations. */ NS_SWIFT_NAME(ListAdapterUpdaterDelegate) @protocol IGListAdapterUpdaterDelegate <NSObject> /** Notifies the delegate that the updater will call `-[UICollectionView performBatchUpdates:completion:]`. @param listAdapterUpdater The adapter updater owning the transition. @param collectionView The collection view that will perform the batch updates. @param fromObjects The items transitioned from in the batch updates, if any. @param toObjects The items transitioned to in the batch updates, if any. @param listIndexSetResults The diffing result of indices to be inserted/removed/updated/moved/etc. */ - (void) listAdapterUpdater:(IGListAdapterUpdater *)listAdapterUpdater willPerformBatchUpdatesWithCollectionView:(UICollectionView *)collectionView fromObjects:(nullable NSArray <id<IGListDiffable>> *)fromObjects toObjects:(nullable NSArray <id<IGListDiffable>> *)toObjects listIndexSetResult:(nullable IGListIndexSetResult *)listIndexSetResults; /** Notifies the delegate that the updater successfully finished `-[UICollectionView performBatchUpdates:completion:]`. @param listAdapterUpdater The adapter updater owning the transition. @param updates The batch updates that were applied to the collection view. @param collectionView The collection view that performed the batch updates. @note This event is called in the completion block of the batch update. */ - (void)listAdapterUpdater:(IGListAdapterUpdater *)listAdapterUpdater didPerformBatchUpdates:(IGListBatchUpdateData *)updates collectionView:(UICollectionView *)collectionView; /** Notifies the delegate that the updater will call `-[UICollectionView insertItemsAtIndexPaths:]`. @param listAdapterUpdater The adapter updater owning the transition. @param indexPaths An array of index paths that will be inserted. @param collectionView The collection view that will perform the insert. @note This event is only sent when outside of `-[UICollectionView performBatchUpdates:completion:]`. */ - (void)listAdapterUpdater:(IGListAdapterUpdater *)listAdapterUpdater willInsertIndexPaths:(NSArray<NSIndexPath *> *)indexPaths collectionView:(UICollectionView *)collectionView; /** Notifies the delegate that the updater will call `-[UICollectionView deleteItemsAtIndexPaths:]`. @param listAdapterUpdater The adapter updater owning the transition. @param indexPaths An array of index paths that will be deleted. @param collectionView The collection view that will perform the delete. @note This event is only sent when outside of `-[UICollectionView performBatchUpdates:completion:]`. */ - (void)listAdapterUpdater:(IGListAdapterUpdater *)listAdapterUpdater willDeleteIndexPaths:(NSArray<NSIndexPath *> *)indexPaths collectionView:(UICollectionView *)collectionView; /** Notifies the delegate that the updater will call `-[UICollectionView moveItemAtIndexPath:toIndexPath:]` @param listAdapterUpdater The adapter updater owning the transition. @param fromIndexPath The index path of the item that will be moved. @param toIndexPath The index path to move the item to. @param collectionView The collection view that will perform the move. @note This event is only sent when outside of `-[UICollectionView performBatchUpdates:completion:]`. */ - (void)listAdapterUpdater:(IGListAdapterUpdater *)listAdapterUpdater willMoveFromIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath collectionView:(UICollectionView *)collectionView; /** Notifies the delegate that the updater will call `-[UICollectionView reloadItemsAtIndexPaths:]`. @param listAdapterUpdater The adapter updater owning the transition. @param indexPaths An array of index paths that will be reloaded. @param collectionView The collection view that will perform the reload. @note This event is only sent when outside of `-[UICollectionView performBatchUpdates:completion:]`. */ - (void)listAdapterUpdater:(IGListAdapterUpdater *)listAdapterUpdater willReloadIndexPaths:(NSArray<NSIndexPath *> *)indexPaths collectionView:(UICollectionView *)collectionView; /** Notifies the delegate that the updater will call `-[UICollectionView reloadSections:]`. @param listAdapterUpdater The adapter updater owning the transition. @param sections The sections that will be reloaded @param collectionView The collection view that will perform the reload. @note This event is only sent when outside of `-[UICollectionView performBatchUpdates:completion:]`. */ - (void)listAdapterUpdater:(IGListAdapterUpdater *)listAdapterUpdater willReloadSections:(NSIndexSet *)sections collectionView:(UICollectionView *)collectionView; /** Notifies the delegate that the updater will call `-[UICollectionView reloadData]`. @param listAdapterUpdater The adapter updater owning the transition. @param collectionView The collection view that will be reloaded. */ - (void)listAdapterUpdater:(IGListAdapterUpdater *)listAdapterUpdater willReloadDataWithCollectionView:(UICollectionView *)collectionView; /** Notifies the delegate that the updater successfully called `-[UICollectionView reloadData]`. @param listAdapterUpdater The adapter updater owning the transition. @param collectionView The collection view that reloaded. */ - (void)listAdapterUpdater:(IGListAdapterUpdater *)listAdapterUpdater didReloadDataWithCollectionView:(UICollectionView *)collectionView; /** Notifies the delegate that the collection view threw an exception in `-[UICollectionView performBatchUpdates:completion:]`. @param listAdapterUpdater The adapter updater owning the transition. @param collectionView The collection view being updated. @param exception The exception thrown by the collection view. @param fromObjects The items transitioned from in the diff, if any. @param toObjects The items transitioned to in the diff, if any. @param diffResult The diff result that were computed from `fromObjects` and `toObjects`. @param updates The batch updates that were applied to the collection view. */ - (void)listAdapterUpdater:(IGListAdapterUpdater *)listAdapterUpdater collectionView:(UICollectionView *)collectionView willCrashWithException:(NSException *)exception fromObjects:(nullable NSArray *)fromObjects toObjects:(nullable NSArray *)toObjects diffResult:(IGListIndexSetResult *)diffResult updates:(IGListBatchUpdateData *)updates; @end NS_ASSUME_NONNULL_END
jjbourdev/IGListKit
Examples/Examples-macOS/Pods/Target Support Files/IGListDiffKit/IGListDiffKit-umbrella.h
<gh_stars>1-10 /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #ifdef __OBJC__ #import <Cocoa/Cocoa.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "IGListAssert.h" #import "IGListBatchUpdateData.h" #import "IGListCompatibility.h" #import "IGListDiff.h" #import "IGListDiffable.h" #import "IGListDiffKit.h" #import "IGListExperiments.h" #import "IGListIndexPathResult.h" #import "IGListIndexSetResult.h" #import "IGListMacros.h" #import "IGListMoveIndex.h" #import "IGListMoveIndexPath.h" #import "NSNumber+IGListDiffable.h" #import "NSString+IGListDiffable.h" FOUNDATION_EXPORT double IGListDiffKitVersionNumber; FOUNDATION_EXPORT const unsigned char IGListDiffKitVersionString[];
jjbourdev/IGListKit
Source/IGListKit/Internal/IGListAdapterInternal.h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import <IGListKit/IGListAdapter.h> #import <IGListKit/IGListBatchContext.h> #import <IGListKit/IGListCollectionContext.h> #import "IGListAdapter+UICollectionView.h" #import "IGListAdapterProxy.h" #import "IGListDisplayHandler.h" #import "IGListSectionMap.h" #import "IGListWorkingRangeHandler.h" NS_ASSUME_NONNULL_BEGIN /// Generate a string representation of a reusable view class when registering with a UICollectionView. NS_INLINE NSString *IGListReusableViewIdentifier(Class viewClass, NSString * _Nullable kind, NSString * _Nullable givenReuseIdentifier) { return [NSString stringWithFormat:@"%@%@%@", kind ?: @"", givenReuseIdentifier ?: @"", NSStringFromClass(viewClass)]; } @interface IGListAdapter () < IGListCollectionContext, IGListBatchContext > { __weak UICollectionView *_collectionView; BOOL _isDequeuingCell; BOOL _isSendingWorkingRangeDisplayUpdates; } @property (nonatomic, strong) id <IGListUpdatingDelegate> updater; @property (nonatomic, strong, readonly) IGListSectionMap *sectionMap; @property (nonatomic, strong, readonly) IGListDisplayHandler *displayHandler; @property (nonatomic, strong, readonly) IGListWorkingRangeHandler *workingRangeHandler; @property (nonatomic, strong, nullable) IGListAdapterProxy *delegateProxy; @property (nonatomic, strong, nullable) UIView *emptyBackgroundView; // we need to special case interactive section moves that are moved to the last position @property (nonatomic) BOOL isLastInteractiveMoveToLastSectionIndex; /** When making object updates inside a batch update block, delete operations must use the section /before/ any moves take place. This includes when other objects are deleted or inserted ahead of the section controller making the mutations. In order to account for this we must track when the adapter is in the middle of an update block as well as the section controller mapping prior to the transition. Note that the previous section controller map is destroyed as soon as a transition is finished so there is no dangling objects or section controllers. */ @property (nonatomic, assign) BOOL isInUpdateBlock; @property (nonatomic, strong, nullable) IGListSectionMap *previousSectionMap; /** Set of cell identifiers registered with the list context. Identifiers are constructed with the `IGListReusableViewIdentifier` function. */ @property (nonatomic, strong) NSMutableSet<NSString *> *registeredCellIdentifiers; @property (nonatomic, strong) NSMutableSet<NSString *> *registeredNibNames; @property (nonatomic, strong) NSMutableSet<NSString *> *registeredSupplementaryViewIdentifiers; @property (nonatomic, strong) NSMutableSet<NSString *> *registeredSupplementaryViewNibNames; - (void)mapView:(__kindof UIView *)view toSectionController:(IGListSectionController *)sectionController; - (nullable IGListSectionController *)sectionControllerForView:(__kindof UIView *)view; - (void)removeMapForView:(__kindof UIView *)view; - (NSArray *)indexPathsFromSectionController:(IGListSectionController *)sectionController indexes:(NSIndexSet *)indexes usePreviousIfInUpdateBlock:(BOOL)usePreviousIfInUpdateBlock; - (nullable NSIndexPath *)indexPathForSectionController:(IGListSectionController *)controller index:(NSInteger)index usePreviousIfInUpdateBlock:(BOOL)usePreviousIfInUpdateBlock; @end NS_ASSUME_NONNULL_END
jjbourdev/IGListKit
Tests/Objects/IGTestDelegateDataSource.h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import <Foundation/Foundation.h> #import <IGListKit/IGListAdapterDataSource.h> #import "IGListTestCase.h" @class IGTestDelegateController; @class IGTestObject; @interface IGTestDelegateDataSource : NSObject <IGListTestCaseDataSource> @property (nonatomic, copy) NSArray <IGTestObject *> *objects; @property (nonatomic, copy) void (^cellConfigureBlock)(IGTestDelegateController *); @end
muhajirrr/fp_sisop_xv6
split.c
<reponame>muhajirrr/fp_sisop_xv6 #include "types.h" #include "stat.h" #include "user.h" #include "fcntl.h" #include "fs.h" int isDirectory(char *s) { struct stat st; int fd = open(s, O_RDONLY); fstat(fd, &st); int res; if (st.type == T_DIR) res = 1; else res = 0; close(fd); return res; } void split(char *s, int bsize) { int fs, fd, n; char buf[bsize]; if (isDirectory(s)) { printf(1, "split: %s is a directory\n", s); return; } else { if ((fs = open(s, O_RDONLY)) < 0) { printf(1, "cp: cannot open %s\n", s); return; } char cname = 'a'; char fname[10]; while ((n = read(fs, buf, sizeof(buf))) > 0) { memmove(fname, &cname, 1); fname[strlen(fname)] = '\0'; fd = open(fname, O_CREATE|O_RDWR); write(fd, buf, n); close(fd); cname++; } close(fs); } } int main(int argc, char *argv[]) { if (argc < 2) printf(1, "Split Usage..."); else if (!strcmp(argv[2], "-b")) split(argv[1], atoi(argv[3])); exit(); }
muhajirrr/fp_sisop_xv6
touch.c
<filename>touch.c #include "types.h" #include "stat.h" #include "user.h" #include "fcntl.h" int main(int argc, char *argv[]) { if (argc < 2) { printf(2, "Help ...\n"); } else { int i; for (i = 1; i < argc; i++) { if (open(argv[i], O_CREATE) == -1) { printf(2,"creating file failed..\n"); } } } exit(); }
muhajirrr/fp_sisop_xv6
cp.c
<reponame>muhajirrr/fp_sisop_xv6 #include "types.h" #include "stat.h" #include "user.h" #include "fcntl.h" #include "fs.h" char *getFileName(char *s) { char *filename = s; char *temp = s; int i; for (i = strlen(temp); i >= 0; i--) { if (temp[i] == '/') { filename = &temp[i+1]; break; } } return filename; } int isDirectory(char *s) { struct stat st; int fd = open(s, O_RDONLY); fstat(fd, &st); int res; if (st.type == T_DIR) res = 1; else res = 0; close(fd); return res; } void copy_one(char *src, char *dest) { int fs, fd, n; char buffer[512]; if (isDirectory(src)) { printf(1, "cp: -r not specified; omitting directory '%s'\n", src); return; } else { char *newdest = (char *) malloc(strlen(getFileName(src))+strlen(dest)+2); strcpy(newdest, dest); if (isDirectory(dest)) { if (dest[strlen(dest)-1] != '/') strcat(newdest, "/"); strcat(newdest, getFileName(src)); } else if (dest[strlen(dest)-1] == '/') { printf(1, "cp: %s is not a directory\n", dest); return; } if ((fs = open(src, O_RDONLY)) < 0) { printf(1, "cp: cannot open %s\n", src); return; } if ((fd = open(newdest, O_CREATE|O_RDWR)) < 0) { printf(1, "cp: cannot open %s\n", dest); return; } while ((n = read(fs, buffer, sizeof(buffer))) > 0) { write(fd, buffer, n); } close(fs); close(fd); } } void copy_all(char *path) { char buf[512], *p; int fd; struct dirent de; if((fd = open(".", 0)) < 0){ printf(2, "cp: cannot open %s\n", "."); return; } strcpy(buf, "."); p = buf+strlen(buf); *p = '/'; p++; while(read(fd, &de, sizeof(de)) == sizeof(de)) { if(de.inum == 0 || !strcmp(de.name, ".") || !strcmp(de.name, "..")) continue; memmove(p, de.name, DIRSIZ); p[DIRSIZ] = 0; copy_one(buf, path); } close(fd); } void copy_recurse(char *src, char *dest) { int fs; char *p, buf[512], bufdir[512]; struct dirent de; if ((fs = open(src, O_RDONLY)) < 0) { printf(2, "cp: cannot open %s\n", src); return; } if (!isDirectory(src)) { copy_one(src, dest); } else { strcpy(bufdir, dest); if (dest[strlen(dest)-1] != '/') strcat(bufdir, "/"); strcat(bufdir, getFileName(src)); mkdir(bufdir); strcpy(buf, src); p = buf+strlen(buf); *p = '/'; p++; while(read(fs, &de, sizeof(de)) == sizeof(de)) { if(de.inum == 0 || !strcmp(de.name, ".") || !strcmp(de.name, "..")) continue; memmove(p, de.name, strlen(de.name)); p[strlen(de.name)] = 0; if (isDirectory(buf)) copy_recurse(buf, bufdir); else copy_one(buf, bufdir); } } } int main(int argc, char *argv[]) { if (argc < 2) { printf(1, "help..\n"); exit(); } else if (argc < 3) { printf(1, "cp: missing destination file operand after %s\n", argv[1]); exit(); } if (!strcmp(argv[1], "*")) copy_all(argv[2]); else if (!strcmp(argv[1], "-r")) copy_recurse(argv[2], argv[3]); else copy_one(argv[1], argv[2]); exit(); }
muhajirrr/fp_sisop_xv6
rm.c
#include "types.h" #include "stat.h" #include "user.h" #include "fcntl.h" #include "fs.h" void rm_one(char *s) { if (unlink(s) < 0) { printf(2, "rm: %s failed to delete\n", s); return; } } void rm_recurse(char *dir) { int fd; char buf[512], *p; struct dirent de; struct stat st; fd = open(dir, O_RDONLY); fstat(fd, &st); switch (st.type) { case T_FILE: rm_one(dir); break; case T_DIR: strcpy(buf, dir); p = buf+strlen(buf); *p = '/'; p++; while(read(fd, &de, sizeof(de)) == sizeof(de)) { if(de.inum == 0 || !strcmp(de.name, ".") || !strcmp(de.name, "..")) continue; memmove(p, de.name, strlen(de.name)); p[strlen(de.name)] = 0; fstat(open(buf, O_RDONLY), &st); if (st.type == T_FILE) rm_one(buf); else if (st.type == T_DIR) rm_recurse(buf); } break; } unlink(dir); close(fd); } int main(int argc, char *argv[]) { int i; if(argc < 2){ printf(2, "Usage: rm [OPTIONS] files...\n"); exit(); } if (!strcmp(argv[1], "-rf")) { for (i = 2; i < argc; i++) { rm_recurse(argv[2]); } } else { for(i = 1; i < argc; i++){ rm_one(argv[i]); } } exit(); }
Synthetic-Automated-Systems/RUDER_MBOT_RL
libraries/DualG2HighPowerMotorShieldTop/DualG2HighPowerMotorShieldTop.h
#pragma once #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || \ defined(__AVR_ATmega328PB__) || defined (__AVR_ATmega32U4__) #define DUALG2HIGHPOWERMOTORSHIELD_TIMER1_AVAILABLE #endif #include <Arduino.h> class DualG2HighPowerMotorShieldTop { public: // CONSTRUCTORS DualG2HighPowerMotorShieldTop(); DualG2HighPowerMotorShieldTop(unsigned char M3nSLEEP, unsigned char M3DIR, unsigned char M3PWM, unsigned char M3nFAULT, unsigned char M3CS, unsigned char M4nSLEEP, unsigned char M4DIR, unsigned char M4PWM, unsigned char M4nFAULT, unsigned char M4CS); // PUBLIC METHODS void init(); void setM3Speed(int speed); // Set speed for M3. void setM4Speed(int speed); // Set speed for M4. void setSpeeds(int m1Speed, int m2Speed); // Set speed for both M3 and M4. unsigned char getM3Fault(); // Get fault reading from M3. unsigned char getM4Fault(); // Get fault reading from M4. void flipM3(boolean flip); // Flip the direction of the speed for M3. void flipM4(boolean flip); // Flip the direction of the speed for M4. void enableM3Driver(); // Enables the MOSFET driver for M3. void enableM4Driver(); // Enables the MOSFET driver for M4. void enableDrivers(); // Enables the MOSFET drivers for both M3 and M4. void disableM3Driver(); // Puts the MOSFET driver for M3 into sleep mode. void disableM4Driver(); // Puts the MOSFET driver for M4 into sleep mode. void disableDrivers(); // Puts the MOSFET drivers for both M3 and M4 into sleep mode. unsigned int getM3CurrentReading(); unsigned int getM4CurrentReading(); void calibrateM3CurrentOffset(); void calibrateM4CurrentOffset(); void calibrateCurrentOffsets(); unsigned int getM3CurrentMilliamps(int gain); unsigned int getM4CurrentMilliamps(int gain); protected: unsigned int _offsetM3; unsigned int _offsetM4; private: unsigned char _M3PWM; static const unsigned char _M3PWM_TIMER1_PIN = 5; unsigned char _M4PWM; static const unsigned char _M4PWM_TIMER1_PIN = 11; unsigned char _M3nSLEEP; unsigned char _M4nSLEEP; unsigned char _M3DIR; unsigned char _M4DIR; unsigned char _M3nFAULT; unsigned char _M4nFAULT; unsigned char _M3CS; unsigned char _M4CS; static boolean _flipM3; static boolean _flipM4; }; class DualG2HighPowerMotorShieldTop24v14 : public DualG2HighPowerMotorShieldTop { public: using DualG2HighPowerMotorShieldTop::DualG2HighPowerMotorShieldTop; unsigned int getM3CurrentMilliamps(); // Get current reading for M3. unsigned int getM4CurrentMilliamps(); // Get current reading for M4. }; class DualG2HighPowerMotorShieldTop18v18 : public DualG2HighPowerMotorShieldTop { public: using DualG2HighPowerMotorShieldTop::DualG2HighPowerMotorShieldTop; unsigned int getM3CurrentMilliamps(); // Get current reading for M3. unsigned int getM4CurrentMilliamps(); // Get current reading for M4. }; class DualG2HighPowerMotorShieldTop24v18 : public DualG2HighPowerMotorShieldTop { public: using DualG2HighPowerMotorShieldTop::DualG2HighPowerMotorShieldTop; unsigned int getM3CurrentMilliamps(); // Get current reading for M3. unsigned int getM4CurrentMilliamps(); // Get current reading for M4. }; class DualG2HighPowerMotorShieldTop18v22 : public DualG2HighPowerMotorShieldTop { public: using DualG2HighPowerMotorShieldTop::DualG2HighPowerMotorShieldTop; unsigned int getM3CurrentMilliamps(); // Get current reading for M3. unsigned int getM4CurrentMilliamps(); // Get current reading for M4. };
arcangelw/ReactiveAutomaton
Sources/ReactiveAutomaton.h
<reponame>arcangelw/ReactiveAutomaton<filename>Sources/ReactiveAutomaton.h #import <Foundation/Foundation.h> //! Project version number for ReactiveAutomaton. FOUNDATION_EXPORT double ReactiveAutomatonVersionNumber; //! Project version string for ReactiveAutomaton. FOUNDATION_EXPORT const unsigned char ReactiveAutomatonVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <ReactiveAutomaton/PublicHeader.h>
vladimirbelinski/Genetic_algorithm-T1_IA
src/ia.h
/* Arquivo: ia.h Autores: <NAME>, <NAME> e <NAME> Descrição: o presente arquivo faz parte da resolução do Trabalho I do CCR Inteligência Artificial, 2017-1, do curso de Ciência da Computação da Universidade Federal da Fronteira Sul - UFFS, o qual consiste na implementação de um algoritmo genético para calcular a tabela de horários dos CCRs do curso de Ciência da Computação da UFFS. --> ia.h é o arquivo cabeçalho de main.cpp */ #include <map> #include <vector> using namespace std; // Par de inteiros typedef pair<int,int> ii; // Par <Sala, Lista de horários> typedef pair< int, vector<int> > room_schedules; // Estrutura para armazenar e representar uma sala de aula. typedef struct Room { int number; string course; vector<int> available_schedules; } room_t; // Estrutura para armazenar e representar um CCR. typedef struct Subject { int period_quantity; string code, course, professor; } subject_t; // Estrutura para armazenar e representar um horário de aula. // period é o número da aula (de 1 a N, inclusive, dado na entrada) // schedule é o horário da semana, de 0 a 29 typedef struct Schedule { room_t room; subject_t subject; int period, schedule; } schedule_t; // Estrutura para armazenar e representar um indivíduo. typedef struct Person { int fitness = 0, schedules_to_avoid_infringements = 0, morning_night_infringements = 0, consecutive_schedules_infringements = 0, restriction_infringements = 0; vector<schedule_t> schedules; } person_t; // Estrutura para armazenar e representar uma população. typedef struct Population { long fitness = 0; vector<person_t> people; } population_t; // Estrutura para armazenar e representar as // salas e horários disponíveis para // uma tripla de <Professor, Curso, CCR>. struct available_schedules { schedule_t schedule; vector<ii> room_schedule; available_schedules(schedule_t _schedule) { schedule = _schedule; } void add_room_schedule(ii k) { room_schedule.push_back(k); } }; void print_professors(void); void print_room(room_t); void print_rooms(vector<room_t>); void print_courses(void); void print_subject(subject_t subject); void print_subjects(void); void print_schedule(schedule_t); void print_person(person_t); void print_population(population_t); void done_print(population_t); bool room_comp(room_t &,room_t &); // Estrutura auxiliar de comparação // de salas para os maps struct room_t_comp { bool operator()(room_t a, room_t b){ return room_comp(a, b); } }; // Estrutura auxiliar de comparação // de horários para os maps struct schedule_t_comp { bool operator()(schedule_t a, schedule_t b){ int diff = a.subject.professor.compare(b.subject.professor); if(diff) return diff < 0; diff = a.subject.course.compare(b.subject.course); if(diff) return diff < 0; diff = a.subject.code.compare(b.subject.code); if(diff) return diff < 0; return a.subject.period_quantity < b.subject.period_quantity; } }; // Estrutura auxiliar de comparação // de CCRs para os maps struct subject_t_comp { bool operator()(subject_t a, subject_t b){ int diff = a.course.compare(b.course); if (diff) return diff < 0; diff = a.code.compare(b.code); if (diff) return diff < 0; diff = a.professor.compare(b.professor); if(diff) return diff < 0; return a.period_quantity < b.period_quantity; } };
weilLove/LWRouter
LWRouter/Classess/LWRouter.h
// // LWRouter.h // LWRouterDemo // // Created by weil on 2018/11/17. // Copyright © 2018 allyoga. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> //跳转分模态和push两种 typedef NS_ENUM(NSUInteger, YGRouterJumpType) { YGRouterJumpTypePush, YGRouterJumpTypeModal }; @interface LWRouter : NSObject //通过硬编码获取类 + (UIViewController *)router_getControllerFromClass:(NSString *)classNam; /*跳转到目标类 *destinationVc:目标控制器 *sourceVc:源控制器 *jumpType:跳转类型 *animaiton:跳转是否需要动画 *params:跳转到目标界面需要的参数 */ + (void)router_jumpToDestination:(UIViewController *)destinationVc from:(UIViewController *)sourceVc jumpType:(YGRouterJumpType)jumpType animation:(BOOL)animation params:(id)params; /*跳转到目标类 *destinationVc:目标控制器 *sourceVc:源控制器 *jumpType:跳转类型 *animaiton:跳转是否需要动画 *params:跳转到目标界面需要的参数 *callback:回调目标界面传回给源界面的值 */ + (void)router_jumpToDestination:(UIViewController *)destinationVc from:(UIViewController *)sourceVc jumpType:(YGRouterJumpType)jumpType animation:(BOOL)animation params:(id)params callback:(void(^)(id callback))callback; + (void)router_jumpToDestinationWithName:(NSString *)destination from:(UIViewController *)sourceVc jumpType:(YGRouterJumpType)jumpType animation:(BOOL)animation params:(id)params; + (void)router_jumpToDestinationWithName:(NSString *)destination from:(UIViewController *)sourceVc jumpType:(YGRouterJumpType)jumpType animation:(BOOL)animation params:(id)params callback:(void(^)(id callback))callback; @end
pro55series/FirstGame
Player.h
class classPlayer { private: int health, mana, strength, dexterity, stamina; std::string playerName; public: void createCharacter(int, int, int, int, int, std::string); void setHealth(int); void setMana(int); void setStrength(int); void setDexterity(int); void setStamina(int); int showHealth(){return health; } int showMana(){return mana; } int showStrength(){return strength; } int showDexterity(){return dexterity; } int showStamina(){return stamina; } std::string showPlayerName() {return playerName; } int addHealth(); int addMana(); int addStrength(); int addDexterity(); int addStamina(); int getAll(){return health, mana, strength, dexterity, stamina;}; };
mcauser/VCC_GND_F407ZG
mpconfigboard.h
<reponame>mcauser/VCC_GND_F407ZG<gh_stars>1-10 #define MICROPY_HW_BOARD_NAME "VCC-GND STM32F407ZG" #define MICROPY_HW_MCU_NAME "STM32F407ZG" #define MICROPY_HW_FLASH_FS_LABEL "VCCGNDF407ZG" // 1 = use internal flash (1 MByte) // 0 = use onboard SPI flash (512 KByte) Winbond W25X40 #define MICROPY_HW_ENABLE_INTERNAL_FLASH_STORAGE (1) #define MICROPY_HW_HAS_FLASH (1) #define MICROPY_HW_ENABLE_RNG (1) #define MICROPY_HW_ENABLE_RTC (1) #define MICROPY_HW_ENABLE_DAC (1) #define MICROPY_HW_ENABLE_USB (1) #define MICROPY_HW_ENABLE_SDCARD (1) // HSE is 25MHz #define MICROPY_HW_CLK_PLLM (25) // divide external clock by this to get 1MHz #define MICROPY_HW_CLK_PLLN (336) // PLL clock in MHz #define MICROPY_HW_CLK_PLLP (RCC_PLLP_DIV2) // divide PLL clock by this to get core clock #define MICROPY_HW_CLK_PLLQ (7) // divide core clock by this to get 48MHz // The board has a 32kHz crystal for the RTC #define MICROPY_HW_RTC_USE_LSE (1) #define MICROPY_HW_RTC_USE_US (0) // #define MICROPY_HW_RTC_USE_CALOUT (1) // turn on/off PC13 512Hz output // USART1 #define MICROPY_HW_UART1_TX (pin_A9) // PA9,PB6 #define MICROPY_HW_UART1_RX (pin_A10) // PA10,PB7 #define MICROPY_HW_UART1_RTS (pin_A12) #define MICROPY_HW_UART1_CTS (pin_A11) // USART1_CK PA8 // USART2 #define MICROPY_HW_UART2_TX (pin_A2) // PA2,PD5 #define MICROPY_HW_UART2_RX (pin_A3) // PA3,PD6 #define MICROPY_HW_UART2_RTS (pin_A1) // PA1,PD4 #define MICROPY_HW_UART2_CTS (pin_A0) // PA0,PD3 // USART2_CK PA4,PD7 // USART3 #define MICROPY_HW_UART3_TX (pin_D8) // PB10,PC10,PD8 #define MICROPY_HW_UART3_RX (pin_D9) // PB11,PC11,PD9 #define MICROPY_HW_UART3_RTS (pin_D12) // PB14,PD12 #define MICROPY_HW_UART3_CTS (pin_D11) // PB13,PD11 // USART3_CK PB12,PC12,PD10 // UART4 #define MICROPY_HW_UART4_TX (pin_A0) // PA0,PC10 #define MICROPY_HW_UART4_RX (pin_A1) // PA1,PC11 // UART5 #define MICROPY_HW_UART5_TX (pin_C12) // PC12 #define MICROPY_HW_UART5_RX (pin_D2) // PD2 // USART6 #define MICROPY_HW_UART6_TX (pin_C6) // PC6,PG14 #define MICROPY_HW_UART6_RX (pin_C7) // PC7,PG9 #define MICROPY_HW_UART6_RTS (pin_G8) // PG8,PG12 #define MICROPY_HW_UART6_CTS (pin_G13) // PG13,PG15 // USART6_CK PC8,PG7 // I2C busses #define MICROPY_HW_I2C1_SCL (pin_B6) // PB8,PB6 #define MICROPY_HW_I2C1_SDA (pin_B7) // PB9,PB7 // I2C1_SMBA PB5 #define MICROPY_HW_I2C2_SCL (pin_B10) // PB10,PF1 #define MICROPY_HW_I2C2_SDA (pin_B11) // PB11,PF0 // I2C2_SMBA PB12,PF2 #define MICROPY_HW_I2C3_SCL (pin_A8) // PA8 #define MICROPY_HW_I2C3_SDA (pin_C9) // PC9 // I2C3_SMBA PA9 // AT24C08 EEPROM on I2C1 0x50-0x53 // I2S busses - multiplexed with SPI2 and SPI3 // I2S2_CK PB10,PB13 // I2S2_MCK PC6 // I2S2_SD PB15,PC3 // I2S2_WS PB9,PB12 // I2S3_CK PB3,PC10 // I2S3_MCK PC7 // I2S3_SD PB5,PC12 // I2S3_WS PA4,PA15 // SPI busses #define MICROPY_HW_SPI1_NSS (pin_A4) // PA4,PA15 #define MICROPY_HW_SPI1_SCK (pin_A5) // PA5,PB3 #define MICROPY_HW_SPI1_MISO (pin_A6) // PA6,PB4 #define MICROPY_HW_SPI1_MOSI (pin_A7) // PA7,PB5 #define MICROPY_HW_SPI2_NSS (pin_B12) // PB12,PB9 #define MICROPY_HW_SPI2_SCK (pin_B13) // PB13,PB10 #define MICROPY_HW_SPI2_MISO (pin_B14) // PB14,PC2 #define MICROPY_HW_SPI2_MOSI (pin_B15) // PB15,PC3 #define MICROPY_HW_SPI3_NSS (pin_A15) // PA15,PA4 #define MICROPY_HW_SPI3_SCK (pin_B3) // PB3,PC10 #define MICROPY_HW_SPI3_MISO (pin_B4) // PB4,PC11 #define MICROPY_HW_SPI3_MOSI (pin_B5) // PB5,PC12 // CAN busses #define MICROPY_HW_CAN1_TX (pin_B9) // PB9,PD1,PA12 #define MICROPY_HW_CAN1_RX (pin_B8) // PB8,PD0,PA11 #define MICROPY_HW_CAN2_TX (pin_B13) // PB13,PB6 #define MICROPY_HW_CAN2_RX (pin_B12) // PB12,PB5 // DAC // DAC_OUT1 PA4 // DAC_OUT2 PA5 // LEDs #define MICROPY_HW_LED1 (pin_G15) // blue #define MICROPY_HW_LED_ON(pin) (mp_hal_pin_low(pin)) #define MICROPY_HW_LED_OFF(pin) (mp_hal_pin_high(pin)) // If using onboard SPI flash #if !MICROPY_HW_ENABLE_INTERNAL_FLASH_STORAGE // W25X40 SPI Flash = 4 Mbit (512 KByte) #define MICROPY_HW_SPIFLASH_SIZE_BITS (4 * 1024 * 1024) #define MICROPY_HW_SPIFLASH_CS (pin_C4) #define MICROPY_HW_SPIFLASH_SCK (pin_A5) #define MICROPY_HW_SPIFLASH_MISO (pin_A6) #define MICROPY_HW_SPIFLASH_MOSI (pin_A7) #define MICROPY_BOARD_EARLY_INIT VCC_GND_F407ZG_board_early_init void VCC_GND_F407ZG_board_early_init(void); extern const struct _mp_spiflash_config_t spiflash_config; extern struct _spi_bdev_t spi_bdev; #define MICROPY_HW_BDEV_IOCTL(op, arg) ( \ (op) == BDEV_IOCTL_NUM_BLOCKS ? (MICROPY_HW_SPIFLASH_SIZE_BITS / 8 / FLASH_BLOCK_SIZE) : \ (op) == BDEV_IOCTL_INIT ? spi_bdev_ioctl(&spi_bdev, (op), (uint32_t)&spiflash_config) : \ spi_bdev_ioctl(&spi_bdev, (op), (arg)) \ ) #define MICROPY_HW_BDEV_READBLOCKS(dest, bl, n) spi_bdev_readblocks(&spi_bdev, (dest), (bl), (n)) #define MICROPY_HW_BDEV_WRITEBLOCKS(src, bl, n) spi_bdev_writeblocks(&spi_bdev, (src), (bl), (n)) #endif // SD card detect switch #define MICROPY_HW_SDCARD_DETECT_PIN (pin_F10) #define MICROPY_HW_SDCARD_DETECT_PULL (GPIO_PULLUP) #define MICROPY_HW_SDCARD_DETECT_PRESENT (GPIO_PIN_RESET) // 1 - PC10 - DAT2/RES // 2 - PC11 - CD/DAT3/CS // 3 - PD2 - CMD/DI // 4 - VCC - VDD // 5 - PC12 - CLK/SCLK // 6 - GND - VSS // 7 - PC8 - DAT0/D0 // 8 - PC9 - DAT1/RES // 9 SW2 - GND // 10 SW1 - PF10 // USB config #define MICROPY_HW_USB_FS (1) // #define MICROPY_HW_USB_VBUS_DETECT_PIN (pin_A9) // #define MICROPY_HW_USB_OTG_ID_PIN (pin_A10) // Ethernet via RMII #define MICROPY_HW_ETH_MDC (pin_C1) #define MICROPY_HW_ETH_MDIO (pin_A2) #define MICROPY_HW_ETH_RMII_REF_CLK (pin_A1) #define MICROPY_HW_ETH_RMII_CRS_DV (pin_A7) #define MICROPY_HW_ETH_RMII_RXD0 (pin_C4) #define MICROPY_HW_ETH_RMII_RXD1 (pin_C5) #define MICROPY_HW_ETH_RMII_TX_EN (pin_B11) #define MICROPY_HW_ETH_RMII_TXD0 (pin_B12) #define MICROPY_HW_ETH_RMII_TXD1 (pin_B13)
rodriguezg68/ep-oc-mcu
extensions/TimeoutFlag.h
<reponame>rodriguezg68/ep-oc-mcu /* * Mbed-OS Microcontroller Library * Copyright (c) 2021 Embedded Planet * Copyright (c) 2021 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ #ifndef EP_OC_MCU_EXTENSIONS_TIMEOUTFLAG_H_ #define EP_OC_MCU_EXTENSIONS_TIMEOUTFLAG_H_ #include "drivers/Timeout.h" #include "platform/Callback.h" #include <chrono> /* TODO extend this so that it supports both volatile bool and rtos flags. Use templating and create generic flag API + default implementations */ /** Class encapsulating a flag that is set/reset by an IRQ timeout */ class TimeoutFlag { public: TimeoutFlag() { } /** * Start the timeout. If the timeout expires before being reset, the internal * flag will be set to true. Calling this before the timeout occurs resets the timeout with * the new timeout duration * @param[in] timeout Chrono duration of timeout */ void start(std::chrono::microseconds timeout) { _flag = false; _timeout.detach(); _timeout.attach(mbed::callback(this, &TimeoutFlag::on_timeout), timeout); } /** * Stop the timeout. The internal flag will be unchanged if the timeout has not yet occurred */ void stop() { _timeout.detach(); } /** * Returns true if the internal flag is set. ie: the timeout has occurred. */ bool is_set() const { return _flag; } protected: void on_timeout() { _flag = true; } protected: volatile bool _flag = false; mbed::Timeout _timeout; }; #endif /* EP_OC_MCU_EXTENSIONS_TIMEOUTFLAG_H_ */
rodriguezg68/ep-oc-mcu
extensions/PersistentArray.h
<reponame>rodriguezg68/ep-oc-mcu /* * Mbed-OS Microcontroller Library * Copyright (c) 2021 Embedded Planet * Copyright (c) 2021 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ #ifndef EP_OC_MCU_EXTENSIONS_PERSISTENTARRAY_H_ #define EP_OC_MCU_EXTENSIONS_PERSISTENTARRAY_H_ #include "kvstore_global_api.h" #include "platform/mbed_error.h" #include "platform/mbed_assert.h" #include "platform/Span.h" #include "platform/mbed_critical.h" #include "mbed-trace/mbed_trace.h" #include <cstring> #include <stdio.h> namespace ep { /** * Templatized Persistent Array built on top of Mbed's * KVStore API. If KVStore is not available the API will fall back to * non-volatile storage with a default initialized */ template<typename T, ptrdiff_t N> class PersistentArray { public: /** * Initialize a persistent array with a default array of values * @param[in] default_array Array of default values to use * @param[in] key Key to use for kvstore * * @note This value is only used if the persistent variable has not * been accessed before or if the kvstore is unavailable for some reason */ PersistentArray(mbed::Span<T,N> default_array, const char *key, uint32_t flags = 0) : _key(key), _flags(flags) { memcpy(_array, default_array.data(), N*sizeof(T)); } /** * Initialize a persistent array with a default value * @param[in] default_value The default value of the array. Every array element will be set to this value. * @param[in] key Key to use for kvstore * * @note This value is only used if the persistent variable has not * been accessed before or if the kvstore is unavailable for some reason */ PersistentArray(T default_value, const char *key, uint32_t flags = 0) : _key(key), _flags(flags) { memset(_array, default_value, N*sizeof(T)); } /** Destructor */ ~PersistentArray(void) { } /** * Attempts to get the underlying value from KVStore * @retval value Value obtained from KVStore of default if unavailable * @note Interrupt safe. A cached value will be returned if called from an interrupt. */ mbed::Span<T,N> get(void) { /* If we're in an ISR, just return the cached value */ if(!core_util_is_isr_active()) { // Try to access the KVStore partition size_t actual_size; int err = kv_get(_key, _array, N*sizeof(T), &actual_size); /** If we weren't able to get the variable, attempt to set the default value in KVStore */ if(err == MBED_ERROR_ITEM_NOT_FOUND) { mbed_tracef(TRACE_LEVEL_WARN, "PARR", "item \"%s\" not found in kvstore, attempting to set...", _key); this->set(mbed::make_Span(_array)); // Now try to get the key... if this doesn't work we will return default err = kv_get(_key, _array, N*sizeof(T), &actual_size); } if(err) { mbed_tracef(TRACE_LEVEL_WARN, "PARR", "could not get item \"%s\" from kvstore: %d", _key, err); } if(actual_size != N*sizeof(T)) { mbed_tracef(TRACE_LEVEL_WARN, "PARR", "actual size (%u) of kvstore entry did not match expected size (%u)", actual_size, N*sizeof(T)); } } return mbed::make_Span(_array); } /** * Attempts to set the underlying value in KVStore * @param[in] value Value to set * * @note Not interrupt safe */ void set(mbed::Span<T,N> new_value) { memcpy(_array, new_value.data(), new_value.size()*sizeof(T)); /** * Try to access the KVStore partition * If this doesn't work value stays default */ int err = kv_set(_key, _array, N*sizeof(T), _flags); if(err) { mbed_tracef(TRACE_LEVEL_WARN, "PARR", "could not set entry \"%s\": %d", _key, err); } } /** * Checks if the given PersistentVariable already exists in KVStore * @return true if exists, false if not * @note Not interrupt safe */ bool exists() { /* This API cannot be called from an ISR, assert here if so * Otherwise it will assert later on and be harder to find. */ assert(!core_util_is_isr_active()); size_t actual_size; int err = kv_get(_key, _array, sizeof(T), &actual_size); if(err) { // TODO this can also return false if a different error occurs other than "doesn't exist" return false; } else { return true; } } protected: T _array[N]; const char *_key; uint32_t _flags; }; } #endif /* EP_OC_MCU_EXTENSIONS_PERSISTENTARRAY_H_ */
rodriguezg68/ep-oc-mcu
extensions/PersistentVariable.h
<filename>extensions/PersistentVariable.h<gh_stars>1-10 /** * ep-oc-mcu * Embedded Planet Open Core for Microcontrollers * * Built with ARM Mbed-OS * * Copyright (c) 2019 Embedded Planet, Inc. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef EP_OC_MCU_EXTENSIONS_PERSISTENTVARIABLE_H_ #define EP_OC_MCU_EXTENSIONS_PERSISTENTVARIABLE_H_ #include "PersistentArray.h" // TODO think about checking if the value is the same during ::set to prevent unnecessary writes to flash namespace ep { /** * Special case of PersistentArray with only 1 value * Adds assignment and evaluation operators */ template<typename T> class PersistentVariable : public PersistentArray<T, 1> { public: /** Initialize a persistent variable with a default value * @param[in] default_value The default value of this persistent variable * @param[in] key Key to store the persistent variable under * @param[in] flags Creation flags for kvstore API (eg: WRITE_ONCE_FLAG) * * @note This value is only used if the persistent variable has not * been accessed before or if the kvstore is unavailable for some reason */ PersistentVariable(T default_value, const char* key, uint32_t flags = 0) : PersistentArray<T, 1>(default_value, key, flags) { } /** Destructor */ ~PersistentVariable(void) { } /** * Assignment operator for updating the value stored in persistent * memory (if available) */ T &operator= (const T &rhs) { this->set(rhs); return *this->_array; } /** Evaluation operator * * Reads underlying persistent memory and returns current value (or default) */ operator T() { this->get(); return *this->_array; } /** * Alias for PersistentArray::get that returns a simple type */ T get() { PersistentArray<T, 1>::get(); return *this->_array; } /** * Alias for PersistentArray::set that accepts a simple type */ void set(T val) { PersistentArray<T, 1>::set(mbed::make_Span<1, T>(&val)); } }; } #endif /* EP_OC_MCU_EXTENSIONS_PERSISTENTVARIABLE_H_ */
hlef/xmotd
main.c
<gh_stars>0 /* xmotd is a message of the day displayer for X11 and dumb-terminals * * It displays a logo in the top-left corner, a 3-line title to its * right and a text-widget (optionally a HTML widget) for displaying * the message, just below. The motd filename(s) are supplied on the * command-line. A single button is used to sequentailly access the * motd(s) and to dismiss the browser when all the messages have been * viewed. A label displays the time of the file being viewed and * (optionally) the filename. It has options for automatically popping * down w/o user intervention and other features which I can't be * bothered to type-in here and would rather have you look at the * man-page or http://www.ee.ryerson.ca:8080/~elf/xmotd.html * */ /* $Id: main.c,v 1.19 2003/02/14 00:35:03 elf Exp elf $ */ /* * Copyright 1993-97, 1999, 2003 <NAME> <<EMAIL>> * * Permission to use, copy, hack, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. This application is presented as is * without any implied or written warranty. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * libhtmlw is copyright (C) 1993, Board of Trustees of the University * of Illinois. See the file libhtmlw/HTML.c for the complete text of * the NCSA copyright. */ #include <stdio.h> #include <malloc.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <utime.h> #include <errno.h> #include <fcntl.h> #if defined(HPUX) #include <ndir.h> #define dirent direct #else #include <dirent.h> #endif #include <X11/Intrinsic.h> #include <X11/StringDefs.h> #include <X11/Xmu/Editres.h> #ifdef HAVE_XPM #include <X11/xpm.h> #endif #ifdef MOTIF #include <Xm/Text.h> #include <Xm/PushB.h> #include <Xm/Form.h> #include <Xm/Label.h> #include <Xm/Separator.h> #else #include <X11/Shell.h> #include <X11/Xaw/AsciiText.h> #include <X11/Xaw/Command.h> #include <X11/Xaw/Form.h> #include <X11/Xaw/Label.h> #endif #ifdef HAVE_HTML #include <HTML.h> #endif #define MIN_SLEEP_PERIOD 60 /* in seconds */ #define HOURS_TO_SECS 3600.0 #include "maindefs.h" #include "appdefs.h" #include "main.h" extern time_t motdChanged(); extern void nextMessage(Widget w, caddr_t call_data, caddr_t client_data); extern void AnchorCallbackProc(Widget w, caddr_t call_data, caddr_t client_data); /* browser.c */ extern void loadLogo(char *logo, Pixmap *icon_pixmap, Pixel fg, Pixel bg); /* in logo.c */ /* fwd decls*/ XtActionProc reallyQuit(Widget w, XButtonEvent *ev); void Quit(Widget w, caddr_t call_data, caddr_t client_data); void printUsage(char *str); /* usage.c */ int runSilentRunDeep(unsigned slumber); unsigned getAlarmTime(float period); messageptr freeMessage(messageptr msglist); messageptr newMessage(char *file); XtAppContext app_con; Widget topLevel; /* the application widget*/ Widget text, quit; Widget info; XtIntervalId timer; /* pop-down time-out ID */ Pixmap icon_pixmap; app_res_t app_res; /* application resources, in main.h */ /* list of pointers to the messages that will actually be displayed */ messageptr msgslist; int gargc; /* globally accessible argc */ char **gargv; /* globally accessible argv*/ char timeStamp[256]; static int alreadyForked; /* flag to remember if we are already running in the background */ #define offset(field) XtOffset (struct _resources *, field) static XtResource resources[] = { { "always","Always",XtRInt, sizeof(int), offset(always),XtRString, "0"}, { "popdown","Popdown",XtRInt, sizeof(int), offset(pto),XtRString, "0"}, { "usedomains","UseDomains",XtRInt, sizeof(int), offset(usedomains),XtRString, "0"}, { "showfilename","ShowFilename",XtRInt, sizeof(int), offset(showfilename),XtRString, "0"}, { "paranoid","Paranoid",XtRInt, sizeof(int), offset(paranoid),XtRString, "0"}, { "tail","Tail",XtRInt, sizeof(int), offset(tail),XtRString, "0"}, { "bitmaplogo","BitmapLogo",XtRString, sizeof(String), offset(logo),XtRString, NULL}, { "warnfile","Warnfile",XtRString, sizeof(String), offset(warnfile),XtRString, NULL}, { "wakeup","Wakeup",XtRFloat, sizeof(float), offset(periodic),XtRString, "0"}, { "stampfile","Stampfile",XtRString, sizeof(String), offset(stampfile),XtRString, TIMESTAMP}, { "atom","Atom",XtRString, sizeof(String), offset(atomname),XtRString, ATOM}, #ifdef HAVE_HTML { "browser","Browser",XtRString, sizeof(String), offset(browser),XtRString, BROWSER}, #endif }; static XrmOptionDescRec options[] = { { "-always", "always", XrmoptionNoArg, "1"}, { "-showfilename", "showfilename", XrmoptionNoArg, "1"}, { "-usedomains", "usedomains", XrmoptionNoArg, "1"}, { "-paranoid", "paranoid", XrmoptionNoArg, "1"}, { "-tail", "tail", XrmoptionNoArg, "1"}, { "-popdown", "popdown", XrmoptionSepArg, (caddr_t) NULL}, { "-bitmaplogo", "bitmaplogo", XrmoptionSepArg, (caddr_t) NULL}, { "-warnfile", "warnfile", XrmoptionSepArg, (caddr_t) NULL}, { "-wakeup", "wakeup", XrmoptionSepArg, (caddr_t) NULL}, { "-stampfile", "stampfile", XrmoptionSepArg, (caddr_t) NULL}, { "-atom", "atom", XrmoptionSepArg, (caddr_t) NULL}, #ifdef HAVE_HTML { "-browser", "browser", XrmoptionSepArg, (caddr_t) NULL}, #endif }; /* You can use shift + btn1 to quit xmotd (when run with -wakeup)*/ static char shift1Trans[]="#override\n\ Shift<Btn1Down>,Shift<Btn1Up>: reallyquit()"; static XtActionsRec xlations[]={ {"reallyquit", (XtActionProc) reallyQuit}, }; /* when the text widget is mapped and we are in "tail" mode, scroll to the end of the file*/ static char tailTrans[]="#override\n\ <Expose>: end-of-file()"; char * getTimeStampName() { static char buf[256]; sprintf(buf, "%s/%s", getenv("HOME"), app_res.stampfile); if(app_res.usedomains) { char domainame[256]; getdomainname(domainame, 256); strcat(buf, "."); strcat(buf, domainame); } return(buf); } /* convert user-specified wakeup time to seconds (argument to sleep)*/ unsigned getAlarmTime(float period) { unsigned slumber=(period*HOURS_TO_SECS); /* fprintf(stderr,"slumber=%ld\n", slumber);*/ /* limit sleep to 60sec*/ return((slumber<MIN_SLEEP_PERIOD)?MIN_SLEEP_PERIOD:slumber); } /* NOTE: Jul 17 1996: This code doesn't work accurately for some reason; the mod-time fo a file doesn't matchup with the time returned by 'date' (this is on 4.1.3_U1). This is only a problem if the wakeup period is something like 1 minute (which I use for testing) -elf*/ void updateTimeStamp(char *motdfile) { struct utimbuf ut; time_t now; /* fprintf(stderr, "Updating timestamp %s now.\n", getTimeStampName() ); */ now = time((time_t *)NULL); ut.actime = now; ut.modtime = now; if(utime(motdfile,&ut)) { extern int errno; if(errno==ENOENT) /* if the file does not (1st time), create it */ { FILE *fp; if((fp=fopen(motdfile,"w"))==NULL){ perror("xmotd"); } fclose(fp); } else /* some other problem */ { perror("xmotd"); exit(1); } } } XtActionProc reallyQuit(Widget w, XButtonEvent *ev ) { extern char *txtbuf; if(txtbuf) free(txtbuf); if(icon_pixmap) { XFreePixmap(XtDisplay(topLevel), icon_pixmap); } XtDestroyApplicationContext(app_con); /* fprintf(stderr,"Bye.\n");*/ exit(0); } void /*ARGSUSED*/ Quit(Widget w, caddr_t call_data, caddr_t client_data) { extern char *txtbuf; if(!app_res.periodic) { /* we can exit because -wakeup is not specified*/ reallyQuit((Widget)NULL, (XButtonEvent *)NULL ); } else { extern void revisitMessagesAndDisplay(int); XUnmapWindow(XtDisplay(topLevel), XtWindow(topLevel)); XFlush(XtDisplay(topLevel)); if(!alreadyForked) { if(fork()) exit(0); alreadyForked=1; } revisitMessagesAndDisplay(runSilentRunDeep(getAlarmTime(app_res.periodic))); } } messageptr freeMessage(messageptr msglist) { messageptr oldmsg; oldmsg = msglist; msglist = msglist->next; free(oldmsg->file); free(oldmsg); return(msglist); } /*freeMessage*/ messageptr newMessage(char *file) { messageptr newmsg; if (!(newmsg = (messageptr)malloc(sizeof(struct messagenode)))) { perror("xmotd"); exit (2); /*problems, probably no ram HA */ } /*if*/ newmsg->file=(char *)calloc(1,(strlen(file)+1)*sizeof(char)); if(!newmsg->file) { perror("xmotd"); exit(2); } strcpy(newmsg->file, file); newmsg->next = NULL; return(newmsg); } /*newMessage*/ int numFilesToDisplay(int argc, char **argv) { register int numsg=0, i; struct stat motdstat; messageptr newmsg, currentmsg = msgslist; /* i starts at 1 since argv[0] is the program name*/ for(i=1; i<argc; i++) { stat(argv[i], &motdstat); if(motdstat.st_mode & S_IFDIR) /* it's a directory */ { DIR *dir; struct dirent *dp; char name[BUFSIZ]; if ((dir = opendir(argv[i]))) { while (dp = readdir(dir)) { if (dp->d_ino == 0) continue; if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue; strcpy(name, argv[i]); if (name[strlen(name) - 1] != '/') strcat(name, "/"); strcat(name, dp->d_name); if (access(name, 0) < 0) continue; if(motdChanged(name, timeStamp) || app_res.always) { newmsg = newMessage(name); if (!currentmsg) /* first in list */ msgslist = newmsg; else currentmsg->next = newmsg; currentmsg = newmsg; numsg++; } /*if motdchanged*/ } /*while*/ closedir(dir); } /*if opendir*/ } else if(motdChanged(argv[i], timeStamp) || app_res.always) { newmsg = newMessage(argv[i]); if (!currentmsg) /* first in list */ msgslist = newmsg; else currentmsg->next = newmsg; currentmsg = newmsg; numsg++; } } if((numsg || app_res.paranoid || app_res.always) && app_res.warnfile) { newmsg = newMessage(app_res.warnfile); newmsg->next = msgslist; msgslist = newmsg; numsg++; } /*if*/ return numsg; }/* numFilesToDisplay*/ int runSilentRunDeep(unsigned slumber) { int numsg=0; while(1) { int fd; /* fprintf(stderr, "Going to sleep! (Zzzzzzzz...)\n");*/ sleep(slumber); /* fprintf(stderr, "Waking-up! (Yawn...)\n");*/ /* first thing we do after waking up is to see if the user is still logged-in*/ if((fd=open("/dev/console", O_RDONLY, O_RDONLY)<0)) { /* since xmotd can't read from the console we assume user has logged-out, so we exit*/ exit(0); } close(fd); /* next check if any messages need to be displayed, if there aren't any, go back to sleep; otherwise return to display messages*/ if(numsg=numFilesToDisplay(gargc, gargv)) return(numsg); } } main(argc, argv) int argc; char **argv; { extern Boolean atomExists(String); Display *display; register int i, start=0; int numsg; if ((argc > 1) && !(strcmp(argv[1],"-help"))) { printUsage(argv[0]); /* and exit */ } /* Test to see whether we are connected to an X display. If we aren't, we proceed in text-only mode: bare-bones functionality; output to stdout. Why bare-bones, I hear you asking? Well, X does all the command-line options parsing for me and I don't feel like duplicating all that code. So there.*/ if((display=XOpenDisplay((char *)NULL))==NULL) { if(argc<2) { fprintf(stderr, "xmotd: ERROR, missing file.\n"); printUsage(argv[0]); /* and exit */ } else { extern void runInTextMode(); runInTextMode(argc, argv); /* ...and exit... */ } fprintf(stderr,"Never gets here!\n"); exit(0); /* just in case */ } else { XCloseDisplay(display); } /* we have to init the toolkit *before* we check the command-line so we can use X's parsing routines, since -geom options, etc. may be specified, in which case, the motd-filename is *not* the 2nd argument*/ topLevel = XtVaAppInitialize(&app_con, "XMotd", options, XtNumber(options), &argc, argv, fallback_resources, NULL); XtGetApplicationResources(topLevel, (caddr_t) &app_res, resources, XtNumber(resources), (ArgList) NULL, (Cardinal) 0); if(argc<2) { fprintf(stderr,"xmotd: ERROR, missing file\n"); printUsage(argv[0]); /* and exit */ } if(app_res.paranoid && !app_res.warnfile) { fprintf(stderr,"xmotd: ERROR, specified \"-paranoid\" without \"-warnfile\"\n"); printUsage(argv[0]); /* and exit */ } strcpy(timeStamp, getTimeStampName()); gargc=argc; gargv=argv; /* first figure out how many of the files supplied on the command-line we will be actually displaying; i.e. we only show the new ones (unless -always has been specified, in which case we show all of them)*/ numsg=numFilesToDisplay(argc, argv); if(!app_res.periodic && !numsg) { /* if none of the messages need to be displayed and -wakeup not specified */ XtDestroyApplicationContext(app_con); exit(0); } if(app_res.periodic) /*-wakeup or -timeout specified*/ { /*ensure no other copies of xmotd are running*/ if(atomExists(app_res.atomname)){ XtDestroyApplicationContext(app_con); exit(0); } if(fork()) exit(0); /*we have to daemonize ourselves*/ alreadyForked=1; /* make a note of it */ if(!numsg) { /* if no messages to be displayed, we sleep */ numsg=runSilentRunDeep(getAlarmTime(app_res.periodic)); } } createWidgets(numsg); nextMessage((Widget)NULL, (caddr_t)NULL, (caddr_t)NULL); XtAddEventHandler(topLevel, (EventMask)0, True, (XtEventHandler)_XEditResCheckMessages, 0); XtRealizeWidget(topLevel); XtAppMainLoop(app_con); } createWidgets(int anymsg) { Widget form, paned, logo, mlabel, hline; XtTranslations shift1TransTable, tailTransTable; Pixel fg, bg; Arg args[8]; int n; #ifdef MOTIF XmString xmstr; form=XtVaCreateManagedWidget("form", xmFormWidgetClass,topLevel, NULL); #else form=XtVaCreateManagedWidget("form", formWidgetClass,topLevel, XtNresizable, True, NULL); #endif /* ifdef MOTIF */ XtVaGetValues(form, XtNbackground, &bg, XtNforeground, &fg, NULL); loadLogo(app_res.logo, &icon_pixmap, fg, bg); #ifdef MOTIF logo=XtVaCreateManagedWidget("logo", xmLabelWidgetClass, form, XmNleftAttachment, XmATTACH_FORM, XmNtopAttachment, XmATTACH_FORM, XmNlabelType, XmPIXMAP, XmNlabelPixmap, icon_pixmap, XmNborderWidth, 0, NULL); mlabel=XtVaCreateManagedWidget("title", xmLabelWidgetClass, form, XmNleftAttachment, XmATTACH_WIDGET, XmNleftWidget, logo, XmNrightAttachment, XmATTACH_FORM, NULL); hline=XtVaCreateManagedWidget("hline", xmSeparatorWidgetClass, form, XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, logo, NULL); quit = XtVaCreateManagedWidget("quit", xmPushButtonWidgetClass, form, XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, logo, XmNlabelType, XmSTRING, XmNtraversalOn, False, /* remove Dismiss button from the Tab group; comment this line out if YOU WANT "Space-bar" to activate the dismiss button*/ NULL); info=XtVaCreateManagedWidget("info", xmLabelWidgetClass, form, XmNleftAttachment, XmATTACH_FORM, XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, quit, XmNlabelType, XmSTRING, NULL); #ifdef HAVE_HTML n = 0; XtSetArg(args[n],XmNtopAttachment, XmATTACH_WIDGET); n++; XtSetArg(args[n],XmNtopWidget, info); n++; XtSetArg(args[n],XmNbottomAttachment, XmATTACH_FORM); n++; text = XtVaCreateManagedWidget("text", htmlWidgetClass, form,NULL); XtSetValues(text,args,n); XtManageChild(text); #else n=0; XtSetArg(args[n], XmNeditMode, XmMULTI_LINE_EDIT); n++; XtSetArg(args[n], XmNeditable, False); n++; XtSetArg(args[n], XmNscrollHorizontal, False); n++; XtSetArg(args[n], XmNscrollLeftSide, True); n++; XtSetArg(args[n], XmNcursorPositionVisible, False); n++; text=XmCreateScrolledText(form, "text", args, n); n=0; XtVaSetValues(XtParent(text), XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, info, XmNbottomAttachment, XmATTACH_FORM, NULL); XtManageChild(text); #endif /* ifdef HAVE_HTML & ifdef MOTIF */ #else logo=XtVaCreateManagedWidget("logo", labelWidgetClass, form, XtNleft, XtChainLeft, XtNright, XtChainLeft, XtNbitmap, icon_pixmap, NULL); mlabel=XtVaCreateManagedWidget("title", labelWidgetClass, form, XtNfromHoriz, logo, NULL); hline=XtVaCreateManagedWidget("hline", labelWidgetClass, form, XtNfromVert, logo, XtNfromVert, mlabel, XtNlabel, (char *)NULL, NULL); quit = XtVaCreateManagedWidget("quit", commandWidgetClass, form, XtNleft, XtChainLeft, XtNright, XtChainLeft, XtNfromVert, logo, NULL); info=XtVaCreateManagedWidget("info", labelWidgetClass, form, XtNright, XtChainLeft, XtNfromVert, quit, XtNresizable, True, NULL); #ifdef HAVE_HTML text = XtVaCreateManagedWidget("text", htmlWidgetClass, form, XtNfromVert, info, XtNwidth, 680, XtNheight, 500, NULL); #else text = XtVaCreateManagedWidget("text", asciiTextWidgetClass, form, XtNfromVert, info, NULL); #endif /* ifdef HAVE_HTML */ if(app_res.tail) { tailTransTable=XtParseTranslationTable(tailTrans); XtOverrideTranslations(text, tailTransTable); } #endif /* ifdef MOTIF */ if((anymsg>1)) { #ifdef MOTIF xmstr=XmStringCreateLocalized(NEXT_MESSAGE_LABEL); XtVaSetValues(quit, XmNlabelString, xmstr, NULL); XmStringFree(xmstr); XtAddCallback(quit, XmNactivateCallback, (XtCallbackProc)nextMessage, 0); #else XtAddCallback(quit, XtNcallback, (XtCallbackProc)nextMessage,(caddr_t)0); XtVaSetValues(quit, XtNlabel, NEXT_MESSAGE_LABEL, NULL); #endif if(app_res.pto) timer=XtAppAddTimeOut(app_con, (unsigned long)(app_res.pto*1000), (XtTimerCallbackProc)nextMessage, (caddr_t) NULL); } else { #ifdef MOTIF xmstr=XmStringCreateLocalized(LAST_MESSAGE_LABEL); XtVaSetValues(quit, XmNlabelString, xmstr, NULL); XmStringFree(xmstr); XtAddCallback(quit, XmNactivateCallback, (XtCallbackProc)Quit, 0); #else XtAddCallback(quit, XtNcallback, (XtCallbackProc)Quit, 0); XtVaSetValues(quit, XtNlabel, LAST_MESSAGE_LABEL, NULL); #endif if(app_res.pto) timer=XtAppAddTimeOut(app_con, (unsigned long)(app_res.pto*1000), (XtTimerCallbackProc)Quit, (caddr_t) NULL); } #ifdef HAVE_HTML XtAddCallback(text, WbNanchorCallback, (XtCallbackProc)AnchorCallbackProc,(caddr_t)0); #endif XtAppAddActions(app_con, xlations, XtNumber(xlations)); shift1TransTable=XtParseTranslationTable(shift1Trans); XtOverrideTranslations(quit, shift1TransTable); }/* createWidgets*/
hlef/xmotd
maindefs.h
/* $Id: maindefs.h,v 1.3 2003/02/14 00:35:22 elf Exp $ */ #define TIMESTAMP ".xmotd" /* the date of this file, in user's * home-directory, is used to * determine whether the motd has * changed and should be displayed*/ #define USAGESTRING "Usage:\n%s [X-toolkit-options] [options] {{file [file2 ...]} {dir/}}\n" #define BAD_BITMAP_MESSAGE "Error reading bitmap file: %s.\nPossible causes:\n the file does not exist (perhaps you mis-typed the name),\n or it is not a valid X bitmap,\n or there is insufficient memory to allocate the bitmap.\n" #define NEXT_MESSAGE_LABEL "Next Message" #define LAST_MESSAGE_LABEL "Dismiss" #define BROWSER "/usr/local/bin/netscape" #define ATOM "xmotd"
hlef/xmotd
xmotd.c
/*$Id: xmotd.c,v 1.20 2003/02/14 00:37:38 elf Exp $*/ /* * Copyright 1994-97, 2003 <NAME> <<EMAIL>> * * Permission to use, copy, hack, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. This application is presented as is * without any implied or written warranty. * */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <stdio.h> #include <malloc.h> #include <time.h> #include <memory.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <utime.h> #include <errno.h> #include <X11/Intrinsic.h> #include <X11/StringDefs.h> #ifdef MOTIF #include <Xm/Text.h> #include <Xm/PushB.h> #include <Xm/Form.h> #include <Xm/Label.h> #include <Xm/Separator.h> #ifdef HAVE_HTML #include <HTML.h> #endif #else #include <X11/Shell.h> #include <X11/Xaw/AsciiText.h> #include <X11/Xaw/Command.h> #include <X11/Xaw/Form.h> #include <X11/Xaw/Label.h> #ifdef HAVE_HTML #include <HTML.h> #endif #endif #include "maindefs.h" #include "main.h" extern time_t motdChanged(); extern messageptr freeMessage(); extern Pixmap icon_pixmap; extern char timeStamp[256]; extern messageptr msgslist;/* list of pointers to the motds requested to be displayed */ extern app_res_t app_res; extern XtAppContext app_con; extern XtIntervalId timer; char *txtbuf; /* file is loaded into this malloc'd pointer */ void /*ARGSUSED*/ nextMessage(Widget w, caddr_t call_data, caddr_t client_data) { char buffer[256]; time_t ftime= time((time_t *)NULL); extern Widget info, quit; #ifdef MOTIF XmString xmstr; #endif /* fprintf(stderr,"nextMessage()\n"); */ if (!msgslist) return; memset(buffer, 0, 256); displayMessage(msgslist->file); updateTimeStamp(getTimeStampName()); /* update the timestamp whenever we pop-up to display a message */ if(app_res.showfilename) /*show the filename */ { sprintf(buffer, "%s (%s)", ctime(&ftime), msgslist->file); } else { sprintf(buffer, "%s", ctime(&ftime)); } *strchr(buffer, '\n')=' '; /* junk the \n at the end*/ #ifdef MOTIF xmstr=XmStringCreateLocalized(buffer); XtVaSetValues(info, XmNlabelString, xmstr, NULL); XmStringFree(xmstr); #else XtVaSetValues(info, XtNlabel, buffer, NULL); #endif /* next time through the loop, we continue at the next message*/ msgslist = freeMessage(msgslist); /*figure out if we are displaying the last message; if we are, then change the button-label to "Dismiss" and re-direct the callback to Quit()*/ if(!msgslist) { extern void Quit(Widget w, caddr_t call_data, caddr_t client_data) ; /* fprintf(stderr, "msgindex=%d, displayed %s (LAST MESSAGE)\n", msgindex, buffer);*/ #ifdef MOTIF xmstr=XmStringCreateLocalized(LAST_MESSAGE_LABEL); XtVaSetValues(quit, XmNlabelString, xmstr, NULL); XmStringFree(xmstr); XtRemoveAllCallbacks(quit, XmNactivateCallback); XtAddCallback(quit, XmNactivateCallback, (XtCallbackProc)Quit, 0); #else XtVaSetValues(quit, XtNlabel, LAST_MESSAGE_LABEL, NULL); XtRemoveAllCallbacks(quit, XtNcallback); XtAddCallback(quit, XtNcallback, (XtCallbackProc)Quit, 0); #endif if(app_res.pto) timer=XtAppAddTimeOut(app_con, (unsigned long)(app_res.pto*1000), (XtTimerCallbackProc)Quit, (caddr_t) NULL); return; } if(app_res.pto) timer=XtAppAddTimeOut(app_con, (unsigned long)(app_res.pto*1000), (XtTimerCallbackProc)nextMessage, (caddr_t) NULL); } void revisitMessagesAndDisplay(int numsg) { extern int gargc; extern char **gargv; extern Widget topLevel, quit; extern void Quit(Widget w, caddr_t call_data, caddr_t client_data); /* fprintf(stderr,"revisitMessagesAndDisplay()\n");*/ if(numsg>1) { #ifdef MOTIF XmString xmstr; xmstr=XmStringCreateLocalized(NEXT_MESSAGE_LABEL); XtVaSetValues(quit, XmNlabelString, xmstr, NULL); XmStringFree(xmstr); XtRemoveAllCallbacks(quit,XmNactivateCallback); XtAddCallback(quit, XmNactivateCallback, (XtCallbackProc)nextMessage, 0); #else XtVaSetValues(quit, XtNlabel, NEXT_MESSAGE_LABEL, NULL); XtRemoveAllCallbacks(quit,XtNcallback); XtAddCallback(quit, XtNcallback, (XtCallbackProc)nextMessage, 0); #endif } /* find and display 1st msg*/ nextMessage((Widget)NULL, (caddr_t)NULL, (caddr_t)NULL); XMapRaised(XtDisplay(topLevel), XtWindow(topLevel)); XFlush(XtDisplay(topLevel)); } int displayMessage(char *filename) { FILE *fp; struct stat motdstat; extern Widget text; /* fprintf(stderr,"displayMessage()\n"); */ #ifdef MOTIF XmString xmstr; #endif /* memset((char *)(&motdstat), 0, sizeof(struct stat));*/ if((fp=fopen(filename,"r"))==NULL) /* Read it in...*/ { perror(filename); return(0); /* no file by this name*/ } stat(filename,&motdstat); if(txtbuf) free(txtbuf); txtbuf=(char *)calloc(1, (motdstat.st_size+1)*sizeof(char)); if(!txtbuf) { extern XtAppContext app_con; perror("xmotd"); XtDestroyApplicationContext(app_con); exit(2); } fread(txtbuf,(int)motdstat.st_size,1,fp); fclose(fp); #ifdef MOTIF #ifdef HAVE_HTML HTMLSetText(text,txtbuf,NULL,NULL,0,NULL,NULL); #else XtVaSetValues(text, XmNvalue, txtbuf, NULL); #endif #else #ifdef HAVE_HTML HTMLSetText(text,txtbuf,NULL,NULL,0,NULL,NULL); #else XtVaSetValues(text, XtNstring, txtbuf, NULL); #endif #endif return(1); }/* displayMessage*/
hlef/xmotd
textmode.c
<gh_stars>0 /* $Id: textmode.c,v 1.7 1998/11/03 22:24:31 elf Exp $ */ /* * Copyright 1993-97 <NAME> <<EMAIL>> * * Permission to use, copy, hack, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. This application is presented as is * without any implied or written warranty. * */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <stdio.h> #include <string.h> #include <malloc.h> #include <sys/stat.h> #include <memory.h> #include <fcntl.h> #include "maindefs.h" void runInTextMode(argc, argv) int argc; char **argv; { register int i, displayed=0; float sleepPeriod=0.0; static int onceAlready; static char buf[256], stampfile[256]; memset(buf, 0, 256); memset(stampfile, 0, 256); strcpy(stampfile, TIMESTAMP); /* default stampfile name */ while(1) { sprintf(buf, "%s/%s", getenv("HOME"), stampfile); for(i=1; i<argc; i++) { /* if it doesn't begin with a '-', its a file */ if(argv[i][0]!='-') { if(motdChanged(argv[i], buf)) { char *txtbuf; struct stat motdstat; FILE *fp; if((fp=fopen(argv[i],"r"))==NULL) { perror(argv[i]); continue; /* get next file */ } stat(argv[i],&motdstat); if(!motdstat.st_size) continue; /* ignore zero-length files */ txtbuf=(char *)calloc(1, (motdstat.st_size+1)*sizeof(char)); if(!txtbuf) { perror("xmotd"); exit(2); } fread(txtbuf,(int)motdstat.st_size,1,fp); fclose(fp); fprintf(stdout, "%s", txtbuf); free(txtbuf); displayed++; } } else /* text mode only understands "-stampfile" and "-wakeup" options apr/15/96*/ { /* this get done everytime we wake-up, maybe we need some check here to the options are parsed only once...*/ if(!strcmp((argv[i]), "-stampfile")) { strcpy(stampfile, (argv[i+1])); /* next param is the filename */ i++; sprintf(buf, "%s/%s", getenv("HOME"), stampfile); /* fprintf(stderr, "stampfile is %s", buf);*/ } else if(!strcmp((argv[i]), "-wakeup")) { /* next param is the period in hrs==> convert to seconds*/ sleepPeriod=(atof(argv[i+1])*3600.0); i++; } else { fprintf(stdout, "%s: WARNING, ignoring %s\n", argv[0], argv[i]); } } } if(displayed) { /* fprintf(stderr, "Displayed file(s)\n");*/ updateTimeStamp(buf); /* reset the timestamp after all files have been read*/ } if(sleepPeriod) { int fd; if(fork()) exit(0); sleep((unsigned)sleepPeriod); /* Check if user is still logged-in by trying to open "/dev/tty". If we can't open the controlling terminal then the user has logged-out (<NAME> _Advanced Programming in the Unix Environment_) and xmotd can exit. */ if((fd=open("/dev/tty", O_RDONLY, O_RDONLY)<0)) { exit(0); } close(fd); displayed=0; /* reset the flag */ } else { exit(0); } } /* while forever */ }
hlef/xmotd
logo.c
/* * Copyright 1993-97 <NAME> <<EMAIL>> * * Permission to use, copy, hack, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. This application is presented as is * without any implied or written warranty. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * libhtmlw is copyright (C) 1993, Board of Trustees of the University * of Illinois. See the file libhtmlw/HTML.c for the complete text of * the NCSA copyright. */ /* $Id: logo.c,v 1.2 1997/07/18 01:23:55 elf Exp $ */ #include <stdio.h> #include <X11/Intrinsic.h> #include <X11/StringDefs.h> #ifdef HAVE_XPM #include <X11/xpm.h> /* default pixmap that goes in the corner*/ #include "xlogo.xpm" #endif #include "maindefs.h" /* default bitmap that goes in the corner*/ #include "xlogo.bm" /* Creates an icon pixmap and returns it in icon_pixmap. If xpm is supported, use it.*/ void loadLogo(char *logo, Pixmap *icon_pixmap, Pixel fg, Pixel bg) { extern Widget topLevel; #ifdef HAVE_XPM Pixmap shape_mask_return; #endif if(logo) { #ifdef MOTIF #ifdef HAVE_XPM int rv=XpmReadFileToPixmap(XtDisplay(topLevel) ,RootWindowOfScreen(XtScreen(topLevel)) ,logo, icon_pixmap ,&shape_mask_return, NULL); if(rv!=BitmapSuccess) { fprintf(stderr,BAD_BITMAP_MESSAGE, logo); exit(-1); } #else *icon_pixmap=XmGetPixmap(XtScreen(topLevel), logo, fg, bg); #endif /* HAVE_XPM*/ #else unsigned int width, height; /* read-in user-specified bitmap*/ int rv=XReadBitmapFile(XtDisplay(topLevel), RootWindowOfScreen(XtScreen(topLevel)), logo, &width, &height, icon_pixmap, (int *)NULL, (int*)NULL); if(rv!=BitmapSuccess) { /* if xpm support is compiled in...*/ #ifdef HAVE_XPM /*... attempt to load it as an xpm file*/ rv=XpmReadFileToPixmap(XtDisplay(topLevel) ,RootWindowOfScreen(XtScreen(topLevel)) ,logo, icon_pixmap ,&shape_mask_return, NULL); #endif if(rv!=BitmapSuccess) { fprintf(stderr,BAD_BITMAP_MESSAGE, logo); exit(-1); } } #endif /*MOTIF*/ } else { #ifdef HAVE_XPM /* display default X pixmap compiled-in*/ XpmCreatePixmapFromData(XtDisplay(topLevel), RootWindowOfScreen(XtScreen(topLevel)), xlogo_xpm, icon_pixmap, &shape_mask_return, NULL); #else /* display default X bitmap compiled-in*/ /* Note: XCreateBitmapFromData doesn't seem to work under Motif for some reason, but XCreatePixmapFromBitmapData works for both, so we use it.*/ *icon_pixmap= XCreatePixmapFromBitmapData(XtDisplay(topLevel), RootWindowOfScreen(XtScreen(topLevel)), xlogo_bits,xlogo_width,xlogo_height, fg, bg, DefaultDepthOfScreen(XtScreen(topLevel))); #if 0 *icon_pixmap= XCreateBitmapFromData(XtDisplay(topLevel), RootWindowOfScreen(XtScreen(topLevel)), xlogo_bits,xlogo_width,xlogo_height); #endif #endif /*HAVE_XPM*/ } }/*loadLogo*/
hlef/xmotd
changed.c
<gh_stars>0 /* Copyright 1993-97 <NAME> <<EMAIL>> * * Permission to use, copy, hack, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. This application is presented as is * without any implied or written warranty. */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* changed.c: utility function for checking the times of 2 files * $Id: changed.c,v 1.4 1997/06/02 11:28:58 elf Exp $ */ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <X11/Intrinsic.h> #include "main.h" extern app_res_t app_res; /* motdChanged() returns time_t of the motd file: if modification time * of motd is greater than the modification time of time-stamp file; * else it returns 0. * */ time_t motdChanged(char *motd, char *stamp) { struct stat motdstat, tsstat; stat(motd, &motdstat); if(stat(stamp, &tsstat)) { extern int errno; if(errno==ENOENT) /* file does not exist if 1st time */ return(motdstat.st_mtime); } if(motdstat.st_mtime <= tsstat.st_mtime) /*Butch Deal*/ return((time_t) 0); if(!motdstat.st_size && !app_res.always) return((time_t) 0); return(motdstat.st_mtime); }
hlef/xmotd
main.h
/* $Id: main.h,v 1.5 1999/11/23 23:01:14 elf Exp $ */ typedef struct _resources { int always; /* flag; if set, ignore .xmotd timestamp */ int pto; /* popdown time-out value in seconds*/ int usedomains; /* do timestamping with .xmotd.domain-name */ int showfilename; /* display the name of the file being viewed next to the date & time */ int paranoid; /* used with -warnfile; always display the warning message */ float periodic; /* if set, xmotd will periodically check the motd files to see if they have changed, and display them accordingly. The value indicates the sleep period in hours (decimals represent minutes)*/ int tail; /* flag; if scroll text widget to end */ String warnfile; /* path to a filename containing a standard warning message that is displayed whenever a motd is displayed*/ String logo; /* path to logo (xbm) */ String stampfile; /* name of the timestamp filename */ String atomname; /* we can force multiple xmotds to run by giving them unique names */ #ifdef HAVE_HTML String browser; /* path to web-browser */ #endif } app_res_t; typedef struct messagenode { /* linked list of messages to display */ char *file; struct messagenode *next; } *messageptr;
hlef/xmotd
patchlevel.h
#define RELEASE 1 #define PATCH 17 #define STATUS "FCS"
hlef/xmotd
appdefs.h
<filename>appdefs.h /* $Id: appdefs.h,v 1.3 1999/08/20 23:45:22 elf Exp $ */ #ifdef MOTIF String fallback_resources[] = { "*form.foreground: black", "*form.background: lightsteelblue3", "*text*fontList: -*-times-bold-r-*-*-*-140-*", "*text*background: lightsteelblue1", #ifdef HAVE_HTML "*text.width: 680", "*text.height: 500", "*text*borderWidth: 1", #else "*text.rows: 25", "*text.columns: 80", "*text*borderWidth: 0", "*text*wordWrap: False", #endif "*title*fontList: -*-times-bold-i-*-*-*-240-*", "*title*width: 500", "*title*borderWidth: 0", "*title*background: lightsteelblue3", "*title*labelString: Message Of The Day\n\n" "*logo*background: lightsteelblue3", "*logo*borderColor: lightsteelblue3", "*logo*borderWidth: 0", "*info*fontList: -*-times-*-r-*-*-*-140-*", "*info*background: lightsteelblue1", "*hline.width: 680", "*hline.background: black", "*quit.fontList: -*-times-bold-i-*-*-*-240-*", "*quit.labelString: Dismiss", "*quit*foreground: dodgerblue4", "*quit*background: lightsteelblue1", NULL, }; #else String fallback_resources[] = { /* "*shell.geometry: +20+20",*/ "*form.foreground: black", "*form.background: lightsteelblue3", "*shapeStyle: oval", "*Text*font: -*-times-bold-r-*-*-*-140-*", "*text*background: lightsteelblue1", #ifdef HAVE_HTML "*Text.width: 680", "*Text.height: 500", "*text*borderWidth: 1", #else "*Text.height: 500", "*Text.width: 680", "*Text*scrollVertical: whenNeeded", "*Text*scrollHorizontal: whenNeeded", "*Text*autoFill: off", "*Text*input: False", #endif "*title.font: -*-times-bold-i-*-*-*-240-*", "*title.width: 500", "*title.borderWidth: 0", "*title.background: lightsteelblue3", "*title.label: Message Of The Day\n\n\n", "*logo.background: lightsteelblue3", "*logo.borderWidth: 0", "*hline.borderWidth: 0", "*hline.height: 2", "*hline.width: 700", "*hline.background: black", "*hline.foreground: black", "*info.font: -*-times-bold-i-*-*-*-120-*", "*info.borderWidth: 0", "*info.background: lightsteelblue3", "*quit.font: -*-times-bold-r-*-*-*-240-*", "*quit.label: Dismiss", "*quit*foreground: dodgerblue4", "*quit*background: lightsteelblue1", NULL, }; #endif
hlef/xmotd
atom.c
<gh_stars>0 /*$Id: atom.c,v 1.2 1999/11/23 00:50:14 elf Exp $*/ /* * Copyright 1999 <NAME> <<EMAIL>> * * Permission to use, copy, hack, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. This application is presented as is * without any implied or written warranty. * */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <stdio.h> #include <sys/types.h> #include <errno.h> #include <pwd.h> #include <X11/Intrinsic.h> #include <X11/StringDefs.h> extern XtAppContext app_con; extern Widget topLevel; /* the application widget*/ /* To prevent multiple copies of xmotd from running (when run with -wakeup) for the same user (this usually happens when a user logs in and out multiple times within the timeout period), we create an Atom in the server so other copies of xmotd can check it returns: True if the atom already exists False if the atom didn't exist (and was created) */ Boolean atomExists(String atomname) { Atom xmotd; struct passwd *pw; static char buffer[256]; pw = getpwuid(getuid()); /* create an unique atom */ sprintf(buffer, "xmotd-%s.%s", atomname, pw->pw_name); /*check if the atom exists*/ xmotd=XInternAtom(XtDisplay(topLevel), buffer, (Boolean)True); /*if the atom doesn't exist*/ if(xmotd==None){ /*create it*/ xmotd=XInternAtom(XtDisplay(topLevel), buffer, (Boolean)False); /* fprintf(stderr,"Created atom: %s\n", buffer); */ return(False); } else{ fprintf(stderr,"xmotd (atomized as %s) is already running-- aborting.\n", atomname); return(True); } } /* atomExists */
hlef/xmotd
browser.c
/* Copyright 1996-97 <NAME> <NAME> <<EMAIL>> * * Permission to use, copy, hack, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. This application is presented as is * without any implied or written warranty. */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* browser.c: * callback procedure to launch a browser (tm) when a hypertext * anchor is activated. * $Id: browser.c,v 1.3 1997/08/28 20:09:27 elf Exp $ */ #ifdef HAVE_HTML #include <stdio.h> #include "maindefs.h" #include "libhtmlw/HTML.h" #include "main.h" extern app_res_t app_res; void __ExecWebBrowser ( char* href ); XtCallbackProc AnchorCallbackProc( Widget w, caddr_t call_data, caddr_t client_data) { WbAnchorCallbackData *anchor_data = ( WbAnchorCallbackData *) client_data; __ExecWebBrowser ( anchor_data->href ); } void __ExecWebBrowser ( char* href ) { static int browser_pid=0; char *default_browser=BROWSER; char *local_browser=BROWSER; if ( ! app_res.browser ) { local_browser=default_browser; } else { local_browser=app_res.browser; } browser_pid = fork(); if ( browser_pid == 0 ) { /* child process */ execlp(local_browser,local_browser,href,NULL); fprintf(stderr,"xmotd: Couldn't exec %s\n", local_browser); } else { int status; (void) wait(&status); } } #endif
hlef/xmotd
usage.c
<gh_stars>0 /* $Id: usage.c,v 1.8 2003/02/14 00:34:14 elf Exp $ */ /* * Copyright 1994-97, 1999, 2003 <NAME> <<EMAIL>> * * Permission to use, copy, hack, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. This application is presented as is * without any implied or written warranty. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <stdio.h> #include "maindefs.h" #include "patchlevel.h" void printUsage(str) char *str; { fprintf(stderr, "This is xmotd %d.%d %s\n", RELEASE, PATCH, STATUS); fprintf(stderr, USAGESTRING, str); fprintf(stderr, "\nValid options are:\n"); fprintf(stderr, " -help display this message\n"); fprintf(stderr, " -always ignore time-stamp and always display motd(s)\n"); fprintf(stderr, " -bitmaplogo file show the bitmap"); #ifdef HAVE_XPM fprintf(stderr, "/pixmap"); #endif fprintf(stderr," in \"file\" instead of X logo\n"); #ifdef HAVE_HTML fprintf(stderr, " -browser program invoke \"program\" when URL is clicked\n"); #endif fprintf(stderr, " -paranoid (used with -warnfile) always show the warning message\n"); fprintf(stderr, " -popdown # automatically pop-down xmotd after waiting # seconds\n"); fprintf(stderr, " -stampfile file use \"file\" as timestamp, instead of \"%s\"\n", TIMESTAMP); fprintf(stderr, " -showfilename show name of the file currently being viewed\n"); fprintf(stderr, " -usedomains append domain-names to timestamp\n"); fprintf(stderr, " -wakeup #.# every # hours, check motd(s) for changes\n"); fprintf(stderr, " -warnfile file show the warning message in \"file\" before motd(s)\n"); fprintf(stderr, " -atom name register xmotd with \"name\"\n"); fprintf(stderr, " -tail scroll & display end of motd file(s)\n"); fprintf(stderr, "\n"); exit(1); }
fgolemo/map
tools/ad_map_access_qgis_python/include/core_python.h
<filename>tools/ad_map_access_qgis_python/include/core_python.h<gh_stars>0 // ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include <Python.h>
fgolemo/map
tools/ad_map_access_qgis_python/include/py_point.h
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include <ad/map/point/Operation.hpp> #include <ad/map/point/Types.hpp> #include "py_physics.h" #include "py_utils.h" template <> PyObject *Py(const ::ad::map::point::ParaPoint &x); template <> inline PyObject *Py(const ::ad::map::point::ParaPointList &x) { return PyVec(x); } template <> inline PyObject *Py(const std::vector<::ad::map::point::ParaPointList> &x) { return PyVec(x); } template <> inline PyObject *Py(const ::ad::map::point::ENUCoordinate &x) { return PyFloat_FromDouble(static_cast<double>(x)); } template <> inline PyObject *Py(const ::ad::map::point::ENUHeading &x) { return PyFloat_FromDouble(static_cast<double>(x)); } template <> inline PyObject *Py(const ::ad::map::point::ENUPoint &p) { return PyTuple_Pack(3, Py(p.x), Py(p.y), Py(p.z)); } template <> inline PyObject *Py(const ::ad::map::point::ENUEdge &x) { return PyVec(x); } template <> inline PyObject *Py(const ::ad::map::point::Longitude &x) { return PyFloat_FromDouble(static_cast<double>(x)); } template <> inline PyObject *Py(const ::ad::map::point::Latitude &x) { return PyFloat_FromDouble(static_cast<double>(x)); } template <> inline PyObject *Py(const ::ad::map::point::Altitude &x) { return PyFloat_FromDouble(static_cast<double>(x)); } template <> inline PyObject *Py(const ::ad::map::point::GeoPoint &x) { return PyTuple_Pack(3, Py(x.longitude), Py(x.latitude), Py(x.altitude)); } template <> inline PyObject *Py(const ::ad::map::point::GeoEdge &x) { return PyVec(x); } template <> inline PyObject *Py(const ::ad::map::point::ECEFCoordinate &x) { return PyFloat_FromDouble(static_cast<double>(x)); } template <> inline PyObject *Py(const ::ad::map::point::ECEFPoint &p) { return PyTuple_Pack(3, Py(p.x), Py(p.y), Py(p.z)); } template <> inline PyObject *Py(const ::ad::map::point::ECEFEdge &x) { return PyVec(x); } inline PyObject *PyConv(const ::ad::map::point::ECEFPoint &x) { ::ad::map::point::GeoPoint geo = ::ad::map::point::toGeo(x); return Py(geo); }
fgolemo/map
tools/ad_map_access_qgis_python/include/py_utils.h
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include <string> #include <vector> #include "./core_python.h" ///////////////////// // Generic Conversion template <typename T> PyObject *Py(const T &x) = delete; template <class T> PyObject *PyVec(const std::vector<T> &obj_vec); template <typename T> PyObject *Py(const std::vector<T> &obj_vec) { return PyVec(obj_vec); } template <class T> PyObject *PyVec(const std::vector<T> &obj_vec) { PyObject *list = PyList_New(0); for (const T &obj : obj_vec) { PyObject *py_obj = ::Py(obj); if (py_obj != nullptr && py_obj != Py_None) { PyList_Append(list, py_obj); } } return list; } ///////////////// // Built-in Types template <> inline PyObject *Py(const bool &x) { return PyBool_FromLong(x ? 1 : 0); } template <> inline PyObject *Py(const uint16_t &x) { return PyLong_FromLong(x); } template <> inline PyObject *Py(const int32_t &x) { return PyLong_FromLong(x); } template <> inline PyObject *Py(const uint32_t &x) { return PyLong_FromLong(x); } template <> inline PyObject *Py(const int64_t &x) { return PyLong_FromLongLong(x); } template <> inline PyObject *Py(const uint64_t &x) { return PyLong_FromUnsignedLongLong(x); } template <> inline PyObject *Py(const double &x) { return PyFloat_FromDouble(x); } template <> inline PyObject *Py(const std::string &x) { return PyString_FromString(x.c_str()); } /////////////////////// // Lists & Dictionaries void PyList(PyObject *list, PyObject *x, bool mandatory = false); void PyDict(PyObject *dict, const char *key, PyObject *x, bool mandatory = false); /////////////////////// // Enums template <typename T> PyObject *PyEnum(const T &x, const std::string &prefix) { auto value = toString(x); if (value.find(prefix) == 0) { return Py(value.substr(prefix.length())); } return Py(value); }
fgolemo/map
ad_map_opendrive_reader/include/opendrive/parser/LaneParser.h
/* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma * de Barcelona (UAB). * Copyright (C) 2019 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ #pragma once #include "opendrive/types.hpp" #include <pugixml.hpp> namespace opendrive { namespace parser { class LaneParser { private: void ParseLane(const pugi::xml_node &xmlNode, std::vector<LaneInfo> &out_lane); void ParseLaneSpeed(const pugi::xml_node &xmlNode, std::vector<LaneSpeed> &out_lane_speed); void ParseLaneLink(const pugi::xml_node &xmlNode, std::unique_ptr<LaneLink> &out_lane_link); void ParseLaneOffset(const pugi::xml_node &xmlNode, std::vector<LaneOffset> &out_lane_offset); void ParseLaneWidth(const pugi::xml_node &xmlNode, std::vector<LaneWidth> &out_lane_width); void ParseLaneRoadMark(const pugi::xml_node &xmlNode, std::vector<LaneRoadMark> &out_lane_mark); public: static void Parse(const pugi::xml_node &xmlNode, Lanes &out_lanes); }; } // parser } // opendrive
fgolemo/map
tools/ad_map_access_qgis_python/include/py_restriction.h
<gh_stars>0 // ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include <ad/map/restriction/Types.hpp> #include "py_physics.h" #include "py_utils.h" template <> PyObject *Py(const ::ad::map::restriction::RoadUserType &x); template <> PyObject *Py(const ::ad::map::restriction::Restriction &restriction); template <> inline PyObject *Py(const ::ad::map::restriction::RestrictionList &x) { return PyVec(x); } template <> PyObject *Py(const ::ad::map::restriction::Restrictions &restrictions); template <> inline PyObject *Py(const ::ad::map::restriction::SpeedLimit &x) { return PyTuple_Pack(3, Py(x.speedLimit), Py(x.lanePiece.minimum), Py(x.lanePiece.maximum)); } template <> inline PyObject *Py(const ::ad::map::restriction::SpeedLimitList &x) { return PyVec(x); }
fgolemo/map
ad_map_opendrive_reader/include/opendrive/parser/RoadLinkParser.h
/* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma * de Barcelona (UAB). * Copyright (C) 2019 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ #pragma once #include "opendrive/types.hpp" #include <pugixml.hpp> namespace opendrive { namespace parser { class RoadLinkParser { private: void ParseLink(const pugi::xml_node &xmlNode, opendrive::RoadLinkInformation *out_link_information); public: static void Parse(const pugi::xml_node &xmlNode, opendrive::RoadLink &out_road_link); }; } }
fgolemo/map
tools/ad_map_access_qgis_python/include/py_lane.h
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include <ad/map/lane/Types.hpp> #include "py_utils.h" template <> PyObject *Py(const ::ad::map::lane::ContactType &x); template <> PyObject *Py(const ::ad::map::lane::LaneType &x); template <> PyObject *Py(const ::ad::map::lane::LaneDirection &x); template <> inline PyObject *Py(const ::ad::map::lane::LaneId &x) { return Py(static_cast<uint64_t>(x)); } PyObject *Py(::ad::map::lane::Lane::ConstPtr lane); template <> PyObject *Py(const ::ad::map::lane::ContactLane &contact_lane);
fgolemo/map
tools/ad_map_access_qgis_python/include/core_py_utils.h
<reponame>fgolemo/map // ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include <ad/map/landmark/Types.hpp> #include <ad/map/lane/Types.hpp> #include <ad/map/point/Types.hpp> #include <string> #include "./core_python.h" #include "./py_utils.h" enum class CoordSys { LLA, ECEF, ENU }; bool ExpectArgs(PyObject *py_args, Py_ssize_t args); bool GetBool(PyObject *py_bool, bool &b); bool GetString(PyObject *py_string, std::string &sz); bool GetInt64(PyObject *py_int64, int64_t &int64); bool GetUInt64(PyObject *py_uint64, uint64_t &uint64); bool GetDouble(PyObject *py_double, double &dbl); bool GetDouble(PyObject *py_double, double min_val, double max_val, double &dbl); ::ad::physics::ParametricValue GetParametricValue(PyObject *py_arg); ::ad::physics::Distance GetDistance(PyObject *py_arg); ::ad::map::point::Longitude GetLongitude(PyObject *py_arg); ::ad::map::point::Latitude GetLatitude(PyObject *py_arg); ::ad::map::point::Altitude GetAltitude(PyObject *py_arg); ::ad::map::lane::LaneId GetLaneId(PyObject *py_lane_id); ::ad::map::point::GeoPoint GetGeoPoint(PyObject *py_geo_point, bool def_altitude_0 = true); bool GetGeoPoints(PyObject *py_geo_points, ::ad::map::point::GeoEdge &geo_pts, bool def_a0 = false); ::ad::map::lane::Lane::ConstPtr GetLane(PyObject *py_lane_id); ::ad::map::landmark::LandmarkId GetLandmarkId(PyObject *py_landmark_id); ::ad::map::landmark::Landmark::ConstPtr GetLandmark(PyObject *py_landmark_id); PyObject *GetLaneEdge(PyObject *py_lane_id, bool left, CoordSys cs); PyObject *GetLaneSubEdge(PyObject *args, bool left, CoordSys cs); PyObject *GetLandmarkPosition(PyObject *py_landmark_id, CoordSys cs);
fgolemo/map
tools/ad_map_access_qgis_python/include/py_access.h
<gh_stars>0 // ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include <ad/map/access/Types.hpp> #include "py_utils.h" template <> inline PyObject *Py(const ::ad::map::access::TrafficType &x) { return PyEnum(x, "::ad::map::access::TrafficType::"); } template <> inline PyObject *Py(const ::ad::map::access::MapMetaData &x) { return PyTuple_Pack(1, Py(x.trafficType)); } template <> inline PyObject *Py(const ::ad::map::access::PartitionId &x) { return Py(static_cast<uint64_t>(x)); }
fgolemo/map
ad_map_opendrive_reader/include/opendrive/parser/GeoReferenceParser.h
<reponame>fgolemo/map /* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma * de Barcelona (UAB). * Copyright (C) 2019 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ #pragma once #include <string> #include "opendrive/types.hpp" namespace opendrive { namespace parser { class GeoReferenceParser { public: static ::opendrive::geom::GeoLocation Parse(const std::string &geo_reference_string); }; } // parser } // opendrive
fgolemo/map
tools/ad_map_access_qgis_python/include/py_landmark.h
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include <ad/map/landmark/Types.hpp> #include "py_utils.h" template <> PyObject *Py(const ::ad::map::landmark::TrafficLightType &x); template <> PyObject *Py(const ::ad::map::landmark::TrafficSignType &x); template <> PyObject *Py(const ::ad::map::landmark::LandmarkType &x); template <> inline PyObject *Py(const ::ad::map::landmark::LandmarkId &x) { return Py(static_cast<uint64_t>(x)); } PyObject *Py(::ad::map::landmark::Landmark::ConstPtr landmark);
fgolemo/map
tools/ad_map_access_qgis_python/include/py_match.h
<gh_stars>0 // ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include <ad/map/match/Types.hpp> #include "py_point.h" #include "py_utils.h" template <> inline PyObject *Py(const ::ad::map::match::MapMatchedPositionType &x) { return PyEnum(x, "::ad::map::match::MapMatchedPositionType::"); } template <> inline PyObject *Py(const ::ad::map::match::MapMatchedPosition &x) { return PyTuple_Pack(8, Py(x.lanePoint.paraPoint), Py(x.type), Py(x.lanePoint.lateralT), Py(x.lanePoint.laneWidth), Py(x.lanePoint.laneLength), PyConv(x.matchedPoint), PyConv(x.queryPoint), Py(x.probability)); } template <> inline PyObject *Py(const ::ad::map::match::MapMatchedPositionConfidenceList &x) { return PyVec(x); }
fgolemo/map
tools/ad_map_access_qgis_python/include/py_physics.h
<gh_stars>0 // ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include <ad/physics/Types.hpp> #include "py_utils.h" template <> inline PyObject *Py(const ::ad::physics::Speed &x) { return PyFloat_FromDouble(static_cast<double>(x)); } template <> inline PyObject *Py(const ::ad::physics::ParametricValue &x) { return PyFloat_FromDouble(static_cast<double>(x)); } template <> inline PyObject *Py(const ::ad::physics::Distance &x) { return PyFloat_FromDouble(static_cast<double>(x)); } template <> inline PyObject *Py(const ::ad::physics::RatioValue &x) { return PyFloat_FromDouble(static_cast<double>(x)); } template <> inline PyObject *Py(const ::ad::physics::Probability &x) { return PyFloat_FromDouble(static_cast<double>(x)); }
eregon/event
ext/event/backend/epoll.c
// Copyright, 2021, by <NAME>. <http://www.codeotaku.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "kqueue.h" #include "backend.h" #include <sys/epoll.h> #include <time.h> #include <errno.h> static VALUE Event_Backend_EPoll = Qnil; static ID id_fileno, id_transfer; enum {EPOLL_MAX_EVENTS = 64}; struct Event_Backend_EPoll { VALUE loop; int descriptor; }; void Event_Backend_EPoll_Type_mark(void *_data) { struct Event_Backend_EPoll *data = _data; rb_gc_mark(data->loop); } void Event_Backend_EPoll_Type_free(void *_data) { struct Event_Backend_EPoll *data = _data; if (data->descriptor >= 0) { close(data->descriptor); } free(data); } size_t Event_Backend_EPoll_Type_size(const void *data) { return sizeof(struct Event_Backend_EPoll); } static const rb_data_type_t Event_Backend_EPoll_Type = { .wrap_struct_name = "Event::Backend::EPoll", .function = { .dmark = Event_Backend_EPoll_Type_mark, .dfree = Event_Backend_EPoll_Type_free, .dsize = Event_Backend_EPoll_Type_size, }, .data = NULL, .flags = RUBY_TYPED_FREE_IMMEDIATELY, }; VALUE Event_Backend_EPoll_allocate(VALUE self) { struct Event_Backend_EPoll *data = NULL; VALUE instance = TypedData_Make_Struct(self, struct Event_Backend_EPoll, &Event_Backend_EPoll_Type, data); data->loop = Qnil; data->descriptor = -1; return instance; } VALUE Event_Backend_EPoll_initialize(VALUE self, VALUE loop) { struct Event_Backend_EPoll *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_EPoll, &Event_Backend_EPoll_Type, data); data->loop = loop; int result = epoll_create1(EPOLL_CLOEXEC); if (result == -1) { rb_sys_fail("epoll_create"); } else { data->descriptor = result; rb_update_max_fd(data->descriptor); } return self; } static inline uint32_t epoll_flags_from_events(int events) { uint32_t flags = 0; if (events & READABLE) flags |= EPOLLIN; if (events & PRIORITY) flags |= EPOLLPRI; if (events & WRITABLE) flags |= EPOLLOUT; flags |= EPOLLRDHUP; flags |= EPOLLONESHOT; return flags; } static inline int events_from_epoll_flags(uint32_t flags) { int events = 0; if (flags & EPOLLIN) events |= READABLE; if (flags & EPOLLPRI) events |= PRIORITY; if (flags & EPOLLOUT) events |= WRITABLE; return events; } struct io_wait_arguments { struct Event_Backend_EPoll *data; int descriptor; int duplicate; }; static VALUE io_wait_ensure(VALUE _arguments) { struct io_wait_arguments *arguments = (struct io_wait_arguments *)_arguments; if (arguments->duplicate >= 0) { epoll_ctl(arguments->data->descriptor, EPOLL_CTL_DEL, arguments->duplicate, NULL); close(arguments->duplicate); } else { epoll_ctl(arguments->data->descriptor, EPOLL_CTL_DEL, arguments->descriptor, NULL); } return Qnil; }; static VALUE io_wait_transfer(VALUE _arguments) { struct io_wait_arguments *arguments = (struct io_wait_arguments *)_arguments; VALUE result = rb_funcall(arguments->data->loop, id_transfer, 0); return INT2NUM(events_from_epoll_flags(NUM2INT(result))); }; VALUE Event_Backend_EPoll_io_wait(VALUE self, VALUE fiber, VALUE io, VALUE events) { struct Event_Backend_EPoll *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_EPoll, &Event_Backend_EPoll_Type, data); struct epoll_event event = {0}; int descriptor = NUM2INT(rb_funcall(io, id_fileno, 0)); int duplicate = -1; event.events = epoll_flags_from_events(NUM2INT(events)); event.data.ptr = (void*)fiber; // fprintf(stderr, "<- fiber=%p descriptor=%d\n", (void*)fiber, descriptor); // A better approach is to batch all changes: int result = epoll_ctl(data->descriptor, EPOLL_CTL_ADD, descriptor, &event); if (result == -1 && errno == EEXIST) { // The file descriptor was already inserted into epoll. duplicate = descriptor = dup(descriptor); rb_update_max_fd(duplicate); if (descriptor == -1) rb_sys_fail("dup"); result = epoll_ctl(data->descriptor, EPOLL_CTL_ADD, descriptor, &event); } if (result == -1) { rb_sys_fail("epoll_ctl"); } struct io_wait_arguments io_wait_arguments = { .data = data, .descriptor = descriptor, .duplicate = duplicate }; return rb_ensure(io_wait_transfer, (VALUE)&io_wait_arguments, io_wait_ensure, (VALUE)&io_wait_arguments); } static int make_timeout(VALUE duration) { if (duration == Qnil) { return -1; } if (FIXNUM_P(duration)) { return NUM2LONG(duration) * 1000L; } else if (RB_FLOAT_TYPE_P(duration)) { double value = RFLOAT_VALUE(duration); return value * 1000; } rb_raise(rb_eRuntimeError, "unable to convert timeout"); } struct select_arguments { struct Event_Backend_EPoll *data; int count; struct epoll_event events[EPOLL_MAX_EVENTS]; int timeout; }; static void * select_internal(void *_arguments) { struct select_arguments * arguments = (struct select_arguments *)_arguments; arguments->count = epoll_wait(arguments->data->descriptor, arguments->events, EPOLL_MAX_EVENTS, arguments->timeout); return NULL; } static void select_internal_without_gvl(struct select_arguments *arguments) { rb_thread_call_without_gvl(select_internal, (void *)arguments, RUBY_UBF_IO, 0); if (arguments->count == -1) { rb_sys_fail("select_internal_without_gvl:epoll_wait"); } } static void select_internal_with_gvl(struct select_arguments *arguments) { select_internal((void *)arguments); if (arguments->count == -1) { rb_sys_fail("select_internal_with_gvl:epoll_wait"); } } VALUE Event_Backend_EPoll_select(VALUE self, VALUE duration) { struct Event_Backend_EPoll *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_EPoll, &Event_Backend_EPoll_Type, data); struct select_arguments arguments = { .data = data, .timeout = 0 }; select_internal_without_gvl(&arguments); if (arguments.count == 0) { arguments.timeout = make_timeout(duration); if (arguments.timeout != 0) { select_internal_with_gvl(&arguments); } } for (int i = 0; i < arguments.count; i += 1) { VALUE fiber = (VALUE)arguments.events[i].data.ptr; VALUE result = INT2NUM(arguments.events[i].events); // fprintf(stderr, "-> fiber=%p descriptor=%d\n", (void*)fiber, events[i].data.fd); rb_funcall(fiber, id_transfer, 1, result); } return INT2NUM(arguments.count); } void Init_Event_Backend_EPoll(VALUE Event_Backend) { id_fileno = rb_intern("fileno"); id_transfer = rb_intern("transfer"); Event_Backend_EPoll = rb_define_class_under(Event_Backend, "EPoll", rb_cObject); rb_define_alloc_func(Event_Backend_EPoll, Event_Backend_EPoll_allocate); rb_define_method(Event_Backend_EPoll, "initialize", Event_Backend_EPoll_initialize, 1); rb_define_method(Event_Backend_EPoll, "io_wait", Event_Backend_EPoll_io_wait, 3); rb_define_method(Event_Backend_EPoll, "select", Event_Backend_EPoll_select, 1); }
eregon/event
ext/event/backend/uring.c
<filename>ext/event/backend/uring.c // Copyright, 2021, by <NAME>. <http://www.codeotaku.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "uring.h" #include "backend.h" #include <liburing.h> #include <poll.h> #include <time.h> static VALUE Event_Backend_URing = Qnil; static ID id_fileno, id_transfer; enum {URING_ENTRIES = 64}; enum {URING_MAX_EVENTS = 64}; struct Event_Backend_URing { VALUE loop; struct io_uring ring; }; void Event_Backend_URing_Type_mark(void *_data) { struct Event_Backend_URing *data = _data; rb_gc_mark(data->loop); } void Event_Backend_URing_Type_free(void *_data) { struct Event_Backend_URing *data = _data; if (data->ring.ring_fd >= 0) { io_uring_queue_exit(&data->ring); data->ring.ring_fd = -1; } free(data); } size_t Event_Backend_URing_Type_size(const void *data) { return sizeof(struct Event_Backend_URing); } static const rb_data_type_t Event_Backend_URing_Type = { .wrap_struct_name = "Event::Backend::URing", .function = { .dmark = Event_Backend_URing_Type_mark, .dfree = Event_Backend_URing_Type_free, .dsize = Event_Backend_URing_Type_size, }, .data = NULL, .flags = RUBY_TYPED_FREE_IMMEDIATELY, }; VALUE Event_Backend_URing_allocate(VALUE self) { struct Event_Backend_URing *data = NULL; VALUE instance = TypedData_Make_Struct(self, struct Event_Backend_URing, &Event_Backend_URing_Type, data); data->loop = Qnil; data->ring.ring_fd = -1; return instance; } VALUE Event_Backend_URing_initialize(VALUE self, VALUE loop) { struct Event_Backend_URing *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_URing, &Event_Backend_URing_Type, data); data->loop = loop; int result = io_uring_queue_init(URING_ENTRIES, &data->ring, 0); if (result < 0) { rb_syserr_fail(-result, "io_uring_queue_init"); } rb_update_max_fd(data->ring.ring_fd); return self; } static inline short poll_flags_from_events(int events) { short flags = 0; if (events & READABLE) flags |= POLLIN; if (events & PRIORITY) flags |= POLLPRI; if (events & WRITABLE) flags |= POLLOUT; flags |= POLLERR; flags |= POLLHUP; return flags; } static inline int events_from_poll_flags(short flags) { int events = 0; if (flags & POLLIN) events |= READABLE; if (flags & POLLPRI) events |= PRIORITY; if (flags & POLLOUT) events |= WRITABLE; return events; } struct io_wait_arguments { struct Event_Backend_URing *data; VALUE fiber; short flags; }; static VALUE io_wait_rescue(VALUE _arguments, VALUE exception) { struct io_wait_arguments *arguments = (struct io_wait_arguments *)_arguments; struct Event_Backend_URing *data = arguments->data; struct io_uring_sqe *sqe = Event_Backend_URing_io_uring_get_sqe(data); // fprintf(stderr, "poll_remove(%p, %p)\n", sqe, (void*)arguments->fiber); io_uring_prep_poll_remove(sqe, (void*)arguments->fiber); io_uring_submit(&data->ring); rb_exc_raise(exception); }; static VALUE io_wait_transfer(VALUE _arguments) { struct io_wait_arguments *arguments = (struct io_wait_arguments *)_arguments; struct Event_Backend_URing *data = arguments->data; VALUE result = rb_funcall(data->loop, id_transfer, 0); // We explicitly filter the resulting events based on the requested events. // In some cases, poll will report events we didn't ask for. short flags = arguments->flags & NUM2INT(result); return INT2NUM(events_from_poll_flags(flags)); }; struct io_uring_sqe *Event_Backend_URing_io_uring_get_sqe(struct Event_Backend_URing *data) { struct io_uring_sqe *sqe = NULL; while (true) { sqe = io_uring_get_sqe(&data->ring); if (sqe != NULL) { return sqe; } // The sqe is full, we need to poll before submitting more events. Event_Backend_URing_select(self, INT2NUM(0)); } } VALUE Event_Backend_URing_io_wait(VALUE self, VALUE fiber, VALUE io, VALUE events) { struct Event_Backend_URing *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_URing, &Event_Backend_URing_Type, data); int descriptor = NUM2INT(rb_funcall(io, id_fileno, 0)); struct io_uring_sqe *sqe = Event_Backend_URing_io_uring_get_sqe(data); short flags = poll_flags_from_events(NUM2INT(events)); // fprintf(stderr, "poll_add(%p, %d, %d, %p)\n", sqe, descriptor, flags, (void*)fiber); io_uring_prep_poll_add(sqe, descriptor, flags); io_uring_sqe_set_data(sqe, (void*)fiber); io_uring_submit(&data->ring); struct io_wait_arguments io_wait_arguments = { .data = data, .fiber = fiber, .flags = flags }; return rb_rescue(io_wait_transfer, (VALUE)&io_wait_arguments, io_wait_rescue, (VALUE)&io_wait_arguments); } inline static void resize_to_capacity(VALUE string, size_t offset, size_t length) { size_t current_length = RSTRING_LEN(string); long difference = (long)(offset + length) - (long)current_length; difference += 1; if (difference > 0) { rb_str_modify_expand(string, difference); } else { rb_str_modify(string); } } inline static void resize_to_fit(VALUE string, size_t offset, size_t length) { size_t current_length = RSTRING_LEN(string); if (current_length < (offset + length)) { rb_str_set_len(string, offset + length); } } VALUE Event_Backend_URing_io_read(VALUE self, VALUE fiber, VALUE io, VALUE buffer, VALUE offset, VALUE length) { struct Event_Backend_URing *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_URing, &Event_Backend_URing_Type, data); resize_to_capacity(buffer, NUM2SIZET(offset), NUM2SIZET(length)); int descriptor = NUM2INT(rb_funcall(io, id_fileno, 0)); struct io_uring_sqe *sqe = Event_Backend_URing_io_uring_get_sqe(data); struct iovec iovecs[1]; iovecs[0].iov_base = RSTRING_PTR(buffer) + NUM2SIZET(offset); iovecs[0].iov_len = NUM2SIZET(length); io_uring_prep_readv(sqe, descriptor, iovecs, 1, 0); io_uring_sqe_set_data(sqe, (void*)fiber); io_uring_submit(&data->ring); // fprintf(stderr, "prep_readv(%p, %d, %ld)\n", sqe, descriptor, iovecs[0].iov_len); int result = NUM2INT(rb_funcall(data->loop, id_transfer, 0)); if (result < 0) { rb_syserr_fail(-result, strerror(-result)); } resize_to_fit(buffer, NUM2SIZET(offset), (size_t)result); return INT2NUM(result); } VALUE Event_Backend_URing_io_write(VALUE self, VALUE fiber, VALUE io, VALUE buffer, VALUE offset, VALUE length) { struct Event_Backend_URing *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_URing, &Event_Backend_URing_Type, data); if ((size_t)RSTRING_LEN(buffer) < NUM2SIZET(offset) + NUM2SIZET(length)) { rb_raise(rb_eRuntimeError, "invalid offset/length exceeds bounds of buffer"); } int descriptor = NUM2INT(rb_funcall(io, id_fileno, 0)); struct io_uring_sqe *sqe = Event_Backend_URing_io_uring_get_sqe(data); struct iovec iovecs[1]; iovecs[0].iov_base = RSTRING_PTR(buffer) + NUM2SIZET(offset); iovecs[0].iov_len = NUM2SIZET(length); io_uring_prep_writev(sqe, descriptor, iovecs, 1, 0); io_uring_sqe_set_data(sqe, (void*)fiber); io_uring_submit(&data->ring); // fprintf(stderr, "prep_writev(%p, %d, %ld)\n", sqe, descriptor, iovecs[0].iov_len); int result = NUM2INT(rb_funcall(data->loop, id_transfer, 0)); if (result < 0) { rb_syserr_fail(-result, strerror(-result)); } return INT2NUM(result); } static struct __kernel_timespec * make_timeout(VALUE duration, struct __kernel_timespec *storage) { if (duration == Qnil) { return NULL; } if (FIXNUM_P(duration)) { storage->tv_sec = NUM2TIMET(duration); storage->tv_nsec = 0; return storage; } else if (RB_FLOAT_TYPE_P(duration)) { double value = RFLOAT_VALUE(duration); time_t seconds = value; storage->tv_sec = seconds; storage->tv_nsec = (value - seconds) * 1000000000L; return storage; } rb_raise(rb_eRuntimeError, "unable to convert timeout"); } static int timeout_nonblocking(struct __kernel_timespec *timespec) { return timespec && timespec->tv_sec == 0 && timespec->tv_nsec == 0; } struct select_arguments { struct Event_Backend_URing *data; int count; struct io_uring_cqe **cqes; struct __kernel_timespec storage; struct __kernel_timespec *timeout; }; static void * select_internal(void *_arguments) { struct select_arguments * arguments = (struct select_arguments *)_arguments; arguments->count = io_uring_wait_cqes(&arguments->data->ring, arguments->cqes, 1, arguments->timeout, NULL); // If waiting resulted in a timeout, there are 0 events. if (arguments->count == -ETIME) { arguments->count = 0; } return NULL; } static int select_internal_without_gvl(struct select_arguments *arguments) { rb_thread_call_without_gvl(select_internal, (void *)arguments, RUBY_UBF_IO, 0); if (arguments->count < 0) { rb_syserr_fail(-arguments->count, "select_internal_without_gvl:io_uring_wait_cqes"); } return arguments->count; } VALUE Event_Backend_URing_select(VALUE self, VALUE duration) { struct Event_Backend_URing *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_URing, &Event_Backend_URing_Type, data); struct io_uring_cqe *cqes[URING_MAX_EVENTS]; // This is a non-blocking operation: int result = io_uring_peek_batch_cqe(&data->ring, cqes, URING_MAX_EVENTS); if (result < 0) { rb_syserr_fail(-result, strerror(-result)); } else if (result == 0) { // We might need to wait for events: struct select_arguments arguments = { .data = data, .cqes = cqes, .timeout = NULL, }; arguments.timeout = make_timeout(duration, &arguments.storage); if (!timeout_nonblocking(arguments.timeout)) { result = select_internal_without_gvl(&arguments); } } // fprintf(stderr, "cqes count=%d\n", result); for (int i = 0; i < result; i += 1) { // If the operation was cancelled, or the operation has no user data (fiber): if (cqes[i]->res == -ECANCELED || cqes[i]->user_data == 0) { continue; } VALUE fiber = (VALUE)io_uring_cqe_get_data(cqes[i]); VALUE result = INT2NUM(cqes[i]->res); // fprintf(stderr, "cqes[i] res=%d user_data=%p\n", cqes[i]->res, (void*)cqes[i]->user_data); io_uring_cqe_seen(&data->ring, cqes[i]); rb_funcall(fiber, id_transfer, 1, result); } return INT2NUM(result); } void Init_Event_Backend_URing(VALUE Event_Backend) { id_fileno = rb_intern("fileno"); id_transfer = rb_intern("transfer"); Event_Backend_URing = rb_define_class_under(Event_Backend, "URing", rb_cObject); rb_define_alloc_func(Event_Backend_URing, Event_Backend_URing_allocate); rb_define_method(Event_Backend_URing, "initialize", Event_Backend_URing_initialize, 1); rb_define_method(Event_Backend_URing, "io_wait", Event_Backend_URing_io_wait, 3); rb_define_method(Event_Backend_URing, "select", Event_Backend_URing_select, 1); rb_define_method(Event_Backend_URing, "io_read", Event_Backend_URing_io_read, 5); rb_define_method(Event_Backend_URing, "io_write", Event_Backend_URing_io_write, 5); }
eregon/event
ext/event/backend/kqueue.c
<filename>ext/event/backend/kqueue.c<gh_stars>0 // Copyright, 2021, by <NAME>. <http://www.codeotaku.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "kqueue.h" #include "backend.h" #include <sys/event.h> #include <sys/ioctl.h> #include <time.h> static VALUE Event_Backend_KQueue = Qnil; static ID id_fileno, id_transfer; enum {KQUEUE_MAX_EVENTS = 64}; struct Event_Backend_KQueue { VALUE loop; int descriptor; }; void Event_Backend_KQueue_Type_mark(void *_data) { struct Event_Backend_KQueue *data = _data; rb_gc_mark(data->loop); } void Event_Backend_KQueue_Type_free(void *_data) { struct Event_Backend_KQueue *data = _data; if (data->descriptor >= 0) { close(data->descriptor); } free(data); } size_t Event_Backend_KQueue_Type_size(const void *data) { return sizeof(struct Event_Backend_KQueue); } static const rb_data_type_t Event_Backend_KQueue_Type = { .wrap_struct_name = "Event::Backend::KQueue", .function = { .dmark = Event_Backend_KQueue_Type_mark, .dfree = Event_Backend_KQueue_Type_free, .dsize = Event_Backend_KQueue_Type_size, }, .data = NULL, .flags = RUBY_TYPED_FREE_IMMEDIATELY, }; VALUE Event_Backend_KQueue_allocate(VALUE self) { struct Event_Backend_KQueue *data = NULL; VALUE instance = TypedData_Make_Struct(self, struct Event_Backend_KQueue, &Event_Backend_KQueue_Type, data); data->loop = Qnil; data->descriptor = -1; return instance; } VALUE Event_Backend_KQueue_initialize(VALUE self, VALUE loop) { struct Event_Backend_KQueue *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_KQueue, &Event_Backend_KQueue_Type, data); data->loop = loop; int result = kqueue(); if (result == -1) { rb_sys_fail("kqueue"); } else { ioctl(result, FIOCLEX); data->descriptor = result; rb_update_max_fd(data->descriptor); } return self; } static int io_add_filters(int descriptor, int ident, int events, VALUE fiber) { int count = 0; struct kevent kevents[2] = {0}; if (events & READABLE) { kevents[count].ident = ident; kevents[count].filter = EVFILT_READ; kevents[count].flags = EV_ADD | EV_ENABLE | EV_ONESHOT; kevents[count].udata = (void*)fiber; // #ifdef EV_OOBAND // if (events & PRIORITY) { // kevents[count].flags |= EV_OOBAND; // } // #endif count++; } if (events & WRITABLE) { kevents[count].ident = ident; kevents[count].filter = EVFILT_WRITE; kevents[count].flags = EV_ADD | EV_ENABLE | EV_ONESHOT; kevents[count].udata = (void*)fiber; count++; } int result = kevent(descriptor, kevents, count, NULL, 0, NULL); if (result == -1) { rb_sys_fail("kevent(register)"); } return events; } static void io_remove_filters(int descriptor, int ident, int events) { int count = 0; struct kevent kevents[2] = {0}; if (events & READABLE) { kevents[count].ident = ident; kevents[count].filter = EVFILT_READ; kevents[count].flags = EV_DELETE; count++; } if (events & WRITABLE) { kevents[count].ident = ident; kevents[count].filter = EVFILT_WRITE; kevents[count].flags = EV_DELETE; count++; } // Ignore the result. kevent(descriptor, kevents, count, NULL, 0, NULL); } struct io_wait_arguments { struct Event_Backend_KQueue *data; int events; int descriptor; }; static VALUE io_wait_rescue(VALUE _arguments, VALUE exception) { struct io_wait_arguments *arguments = (struct io_wait_arguments *)_arguments; io_remove_filters(arguments->data->descriptor, arguments->descriptor, arguments->events); rb_exc_raise(exception); }; static inline int events_from_kqueue_filter(int filter) { if (filter == EVFILT_READ) return READABLE; if (filter == EVFILT_WRITE) return WRITABLE; return 0; } static VALUE io_wait_transfer(VALUE _arguments) { struct io_wait_arguments *arguments = (struct io_wait_arguments *)_arguments; VALUE result = rb_funcall(arguments->data->loop, id_transfer, 0); return INT2NUM(events_from_kqueue_filter(NUM2INT(result))); }; VALUE Event_Backend_KQueue_io_wait(VALUE self, VALUE fiber, VALUE io, VALUE events) { struct Event_Backend_KQueue *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_KQueue, &Event_Backend_KQueue_Type, data); int descriptor = NUM2INT(rb_funcall(io, id_fileno, 0)); struct io_wait_arguments io_wait_arguments = { .events = io_add_filters(data->descriptor, descriptor, NUM2INT(events), fiber), .data = data, .descriptor = descriptor, }; return rb_rescue(io_wait_transfer, (VALUE)&io_wait_arguments, io_wait_rescue, (VALUE)&io_wait_arguments); } static struct timespec * make_timeout(VALUE duration, struct timespec * storage) { if (duration == Qnil) { return NULL; } if (FIXNUM_P(duration)) { storage->tv_sec = NUM2TIMET(duration); storage->tv_nsec = 0; return storage; } else if (RB_FLOAT_TYPE_P(duration)) { double value = RFLOAT_VALUE(duration); time_t seconds = value; storage->tv_sec = seconds; storage->tv_nsec = (value - seconds) * 1000000000L; return storage; } rb_raise(rb_eRuntimeError, "unable to convert timeout"); } static int timeout_nonblocking(struct timespec * timespec) { return timespec && timespec->tv_sec == 0 && timespec->tv_nsec == 0; } struct select_arguments { struct Event_Backend_KQueue *data; int count; struct kevent events[KQUEUE_MAX_EVENTS]; struct timespec storage; struct timespec *timeout; }; static void * select_internal(void *_arguments) { struct select_arguments * arguments = (struct select_arguments *)_arguments; arguments->count = kevent(arguments->data->descriptor, NULL, 0, arguments->events, arguments->count, arguments->timeout); return NULL; } static void select_internal_without_gvl(struct select_arguments *arguments) { rb_thread_call_without_gvl(select_internal, (void *)arguments, RUBY_UBF_IO, 0); if (arguments->count == -1) { rb_sys_fail("select_internal_without_gvl:kevent"); } } static void select_internal_with_gvl(struct select_arguments *arguments) { select_internal((void *)arguments); if (arguments->count == -1) { rb_sys_fail("select_internal_with_gvl:kevent"); } } VALUE Event_Backend_KQueue_select(VALUE self, VALUE duration) { struct Event_Backend_KQueue *data = NULL; TypedData_Get_Struct(self, struct Event_Backend_KQueue, &Event_Backend_KQueue_Type, data); struct select_arguments arguments = { .data = data, .count = KQUEUE_MAX_EVENTS, .storage = { .tv_sec = 0, .tv_nsec = 0 } }; // We break this implementation into two parts. // (1) count = kevent(..., timeout = 0) // (2) without gvl: kevent(..., timeout = 0) if count == 0 and timeout != 0 // This allows us to avoid releasing and reacquiring the GVL. // Non-comprehensive testing shows this gives a 1.5x speedup. arguments.timeout = &arguments.storage; // First do the syscall with no timeout to get any immediately available events: select_internal_with_gvl(&arguments); // If there were no pending events, if we have a timeout, wait for more events: if (arguments.count == 0) { arguments.timeout = make_timeout(duration, &arguments.storage); if (!timeout_nonblocking(arguments.timeout)) { arguments.count = KQUEUE_MAX_EVENTS; select_internal_without_gvl(&arguments); } } for (int i = 0; i < arguments.count; i += 1) { VALUE fiber = (VALUE)arguments.events[i].udata; VALUE result = INT2NUM(arguments.events[i].filter); rb_funcall(fiber, id_transfer, 1, result); } return INT2NUM(arguments.count); } void Init_Event_Backend_KQueue(VALUE Event_Backend) { id_fileno = rb_intern("fileno"); id_transfer = rb_intern("transfer"); Event_Backend_KQueue = rb_define_class_under(Event_Backend, "KQueue", rb_cObject); rb_define_alloc_func(Event_Backend_KQueue, Event_Backend_KQueue_allocate); rb_define_method(Event_Backend_KQueue, "initialize", Event_Backend_KQueue_initialize, 1); rb_define_method(Event_Backend_KQueue, "io_wait", Event_Backend_KQueue_io_wait, 3); rb_define_method(Event_Backend_KQueue, "select", Event_Backend_KQueue_select, 1); }
crs4/ge-k8s
gek8s-node-start-launcher.c
/** * Copyright 2019 CRS4. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> #include <limits.h> // node boostrap script #define BASH_SCRIPT "/gek8s-node-start.sh" /** Print usage and exist reporting an error code */ void print_usage_and_exit(void) { const char *const help = "\nusage: gek8s-node-start-launcher [p1=v1] [p2=v2] ... [pn=vn]\n\n" "pi=vi are pair of property values\n\n"; fprintf(stderr, help); exit(EXIT_FAILURE); } /** Check permissions and call the bootstrap script as root user */ int main(int argc, char *argv[]) { // switch to the root user by setting UID to 0 // This is needed to run the startup node an root fprintf(stderr, "\nChecking root privileges... "); if (setuid(0)) { fprintf(stderr, " ERROR\n"); perror("You need root privileges!\n"); print_usage_and_exit(); } fprintf(stderr, "OK\n"); // build boostrap command char cmd[PATH_MAX]; // no. of args for execvp. We need an extra 2 args: // 1. name of command // 2. NULL pointer to terminate the array const int n_cmd_args = (argc-1)*2 + 2; char *cmd_arguments[n_cmd_args]; cmd_arguments[n_cmd_args - 1] = NULL; // must be NULL-terminated for execvp if (getcwd(cmd, sizeof(cmd)) != NULL) { strcat(cmd, BASH_SCRIPT); cmd_arguments[0] = cmd; for (int i = 1; i < n_cmd_args - 1; i+=2) { cmd_arguments[i] = "-v"; cmd_arguments[i+1] = argv[i]; } } else { perror("Error getting the current working directory\n"); print_usage_and_exit(); } // Execute the bash script with root privileges if(execvp(cmd, cmd_arguments) == -1) { perror("\nError during node boostrap\n"); exit(EXIT_FAILURE); } }
xilletex/MonteCarlo
source.c
<filename>source.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <unistd.h> #define SRAND_REDEF 100000 #define RND_MIN 0 #define RND_MAX 1 static int float_rand_seed_flag = 0; float maybe_pi = 0; float FlortGetRandom(float min, float max) { float ret_value; if (float_rand_seed_flag == 0) { srand((unsigned int)time(NULL)); float_rand_seed_flag = 1; } ret_value = min + (max-min)*((float)rand()/RAND_MAX); return ret_value; } void main(void){ /* main内で使用するauto変数の定義 */ unsigned long long i = 0; float throw_x; float throw_y; float distance; double debug_reg = 0; debug_reg = i / 100; unsigned long long count = 0; /* 試行回数 */ unsigned long long incircle = 0; /* 円の中に入った回数 */ int win = 0; double win_num = 0; printf("Input LOOP number。:"); scanf("%lf", &i); if(i <= 100){ debug_reg = 1; } else if (i >= 100000000){ debug_reg = 10000000; } printf("\n"); do{ count++; if((count % SRAND_REDEF)==0) { float_rand_seed_flag = 0; } throw_x = FlortGetRandom(RND_MIN, RND_MAX); //x座標 throw_y = FlortGetRandom(RND_MIN, RND_MAX); //y座標 distance = sqrt ( (throw_x * throw_x) + (throw_y * throw_y) ); if (distance <= 1.0) { incircle++; }else { ; } /* 推定円周率を更新 */ maybe_pi = (4*((float)incircle / (float)count)); /* ループ中の表示 */ if(fmod(count, debug_reg)==0){ printf("%d回試行を行い、円のなか%d回なので、推定円周率は %.15f %%です。\n", count , incircle, maybe_pi); printf("throw_x:%10lu, throw_y:%10lu, maybe_pi:%10lu\n",throw_x, throw_y, maybe_pi ); usleep(10000); } }while(count != i); printf("\n%d回試行を行い、円内に入ったのが%d回なので、推定円周率は %.15f %%です。\n", count , incircle, maybe_pi); }
KIodine/naiveds
singly-linked-list/main.c
<filename>singly-linked-list/main.c #include <stdio.h> #include <assert.h> #include "sllist.h" #define NL "\n" void basic_test(void){ int ret_code, res; struct sllist *list; list = sll_alloc(); printf("test push"NL); for (int i = 0; i < 8; ++i){ ret_code = sll_push(list, i); assert(ret_code == SLL_OK); } LIST_TRAVERSE(list, node){ //printf("%d ", node->val); } //putchar('\n'); printf("test pop"NL); for (int i = 7; i >= 0; --i){ ret_code = sll_pop(list, &res); assert(ret_code == SLL_OK); //printf("%d " , res); assert(res == i); } //putchar('\n'); printf("test empty pop"NL); ret_code = sll_pop(list, &res); assert(ret_code == SLL_NOELEM); printf("test append"NL); for (int i = 0; i < 8; ++i){ ret_code = sll_append(list, i); assert(ret_code == SLL_OK); } int i = 0; LIST_TRAVERSE(list, n){ assert(n->val == i); ++i; } printf("test get"NL); ret_code = sll_get(list, 3U, &res); assert(ret_code == SLL_OK); assert(res == 3); printf("test delete"NL); ret_code = sll_delete(list, 3); assert(ret_code == SLL_OK); printf("test empty delete"NL); ret_code = sll_delete(list, 3); assert(ret_code == SLL_NOELEM); printf("test reverse"NL); sll_reverse(list); printf("check reverse"NL); LIST_TRAVERSE(list, node){ printf("%d"NL, node->val); } printf("test purge"NL); sll_purge(list); printf("test free"NL); sll_free(list); return; } int main(void){ basic_test(); return 0; }
KIodine/naiveds
hashtable-chain/include/hashmap.h
<filename>hashtable-chain/include/hashmap.h #ifndef HASHMAP_H #define HASHMAP_H #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stddef.h> #include <string.h> #include <assert.h> // copy from <linux/kernel.h> and strip debug stuffs. #define container_of(ptr, type, member) ({ \ void *__mptr = (void *)(ptr); \ ((type *)(__mptr - offsetof(type, member))); }) struct map; struct map_node; typedef uint32_t (*obj_hasher)(struct map_node*); typedef int (*obj_cmp)(struct map_node*, struct map_node*); struct map_node { uint32_t hashval; struct map_node **pprev, *next; }; /* `**pprev` means `where did this object put` */ struct map { obj_hasher hasher; obj_cmp cmp; unsigned int capacity; unsigned int count; unsigned int resize_thres; struct map_node **bucket; }; struct map *map_alloc(unsigned int size_hint, obj_hasher hash, obj_cmp cmp); void map_free(struct map *m); int map_insert(struct map *m, struct map_node *mnode); struct map_node *map_get(struct map *m, struct map_node *hint); int map_delete(struct map *m, struct map_node *mnode); #endif /* HASHMAP_H */
KIodine/naiveds
arrayq/fifoq.c
<reponame>KIodine/naiveds<gh_stars>1-10 #include "fifoq.h" #include <assert.h> static unsigned int round_up_pow_2(unsigned int v){ /* * fill bits lower than the leftmost bit. * the decrement and increment prevents numbers already are * power or 2 doubles. */ v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } struct fifoq *fifoq_alloc(unsigned int size){ struct fifoq *q; size = round_up_pow_2(size); q = calloc(1, sizeof(struct fifoq)); q->arr = malloc(sizeof(int)*(size + 1)); /* extra 1 space for sentinel. */ q->size = size; q->mask = size - 1; /* Ensure it's power of 2. */ assert(((size - 1) & size) == 0); q->front = 0; q->end = 0; return q; } void fifoq_free(struct fifoq *q){ free(q->arr); free(q); return; } int fifoq_push(struct fifoq *q, int val){ if (fifoq_is_full(q)){ return -1; } q->arr[q->front & q->mask] = val; q->front++; return 0; } int fifoq_get(struct fifoq *q, int *res){ if (fifoq_is_empty(q)){ q->front = q->end = 0; return -1; } *res = q->arr[q->end & q->mask]; q->end++; return 0; } int fifoq_put(struct fifoq *q, int val){ if (fifoq_is_full(q)){ return -1; } q->end--; q->arr[q->end & q->mask] = val; return 0; } int fifoq_pop(struct fifoq *q, int *res){ if (fifoq_is_empty(q)){ return -1; } q->front--; *res = q->arr[q->front & q->mask]; return 0; }
KIodine/naiveds
union-find/test/main.c
<reponame>KIodine/naiveds #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "unionfind.h" #define NL "\n" #define ARRAYSZ(arr) (sizeof(arr)/sizeof(arr[0])) static struct ufnode sets[8192]; static void uf_test(void){ static const int arrsz = ARRAYSZ(sets); printf("[union-find] set size=%d"NL, arrsz); for (int i = 0; i < arrsz; ++i){ uf_init_set(&sets[i]); assert(1 == uf_connected(&sets[i], &sets[i])); } /* Test union with other in set. */ for (int i = 0; i < (arrsz - 1); i++){ int un_subj = i + 1; uf_union(&sets[i], &sets[un_subj]); for (int j = 0; j <= i; j++){ /* for each set number smaller/eq than that, test connectivity */ assert(1 == uf_connected(&sets[j], &sets[un_subj])); } for (int j = un_subj + 1; j < arrsz; j++){ /* for others must remain disconnected. */ assert(0 == uf_connected(&sets[un_subj], &sets[j])); } } return; } int main(void){ printf("--- test union-find ---"NL); uf_test(); return 0; }
KIodine/naiveds
intrusive-avltree/include/avldbg.h
#ifndef AVLDBG_H #define AVLDBG_H #include "avltree.h" void avl_print(struct avltree *tree); void avl_validate(struct avltree *tree); #endif /* AVLDBG_H */
KIodine/naiveds
binheap/binheap.c
#include <assert.h> #include <stdlib.h> #include "binheap.h" /* get_parent() get_left() get_right() get_last_parent() sift_down() sift_up() */ /* --- static routines --- */ static inline int get_parent(int cur){ return ((cur + 1) >> 1) - 1; } static inline int get_left(int cur){ return ((cur + 1) << 1) - 1; } static inline int get_right(int cur){ return ((cur + 1) << 1); } static inline int get_last_parent(int len){ return (len - 1) >> 1; } static inline void sift_up(int *arr, int cur){ int parent, tmp; for (; cur != 0;){ parent = get_parent(cur); if (arr[cur] > arr[parent]){ // do swap tmp = arr[cur]; arr[cur] = arr[parent]; arr[parent] = tmp; } else { break; } /* Ensure the procedure ends eventually. */ assert(cur > parent); cur = parent; } return; } static inline void sift_down(int *arr, int cur, int len){ int left, right, subst, tmp; for (;cur < len;){ subst = cur; left = get_left(cur); right = left + 1; /* boundary check & choose subst. */ if (left < len){ subst = left; } if (right < len && (arr[right] > arr[left])){ subst = right; } if (subst == cur){ /* no available child to subst. */ break; } /* try do swap. */ if (arr[subst] > arr[cur]){ /* do swap. */ tmp = arr[subst]; arr[subst] = arr[cur]; arr[cur] = tmp; } else { break; } /* `subst` must be a increasing number. */ assert(subst > cur); cur = subst; } return; } /* --- public routines --- */ void maxheapify(int *arr, int len){ int cur; for (cur = get_last_parent(len); ; cur--){ sift_down(arr, cur, len); if (cur == 0){ break; } } return; } struct binheap *binheap_alloc(size_t cap){ struct binheap *heap; int *arr; heap = calloc(1, sizeof(struct binheap)); if (heap == NULL){ goto heap_alloc_fail; } arr = calloc(1, sizeof(int)*cap); if (arr == NULL){ goto arr_alloc_fail; } heap->arr = arr; heap->count = 0; heap->capacity = cap; return heap; /* Error handling section. */ arr_alloc_fail: free(heap); heap_alloc_fail: return NULL; } void binheap_free(struct binheap *heap){ free(heap->arr); free(heap); return; } int binheap_insert(struct binheap *heap, int val){ int cur; if (heap->count >= heap->capacity){ return -1; } cur = heap->count; heap->arr[cur] = val; heap->count += 1; sift_up(heap->arr, cur); return 0; } int binheap_extract(struct binheap *heap, int *res){ int cur; if (heap->count == 0 || res == NULL){ return -1; } cur = heap->count; /* Return max value and subst with last value in heap. */ *res = heap->arr[0]; heap->arr[0] = heap->arr[cur-1]; heap->count -= 1; sift_down(heap->arr, 0, heap->count); return 0; } // TODO
KIodine/naiveds
skiplist/include/slist_internal.h
<filename>skiplist/include/slist_internal.h<gh_stars>1-10 #ifndef SLIST_INTERNAL_H #define SLIST_INTERNAL_H /* Includes symbols for internal usage only. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #endif
KIodine/naiveds
union-find/src/unionfind.h
#ifndef UNIONFIND_H #define UNIONFIND_H struct ufnode { struct ufnode *parent; int rank; }; void uf_init_set(struct ufnode *node); struct ufnode *uf_find(struct ufnode *node); int uf_connected(struct ufnode *a, struct ufnode *b); int uf_union(struct ufnode *a, struct ufnode *b); #endif
KIodine/naiveds
intrusive-rbtree/main.c
<gh_stars>1-10 #include <stdio.h> #include <assert.h> #include <unistd.h> #include <fcntl.h> #include <stdint.h> #include "rbtree.h" #define NL "\n" #define NINT32 65536 #define TESTFNAME "./testints.bin" struct pair { struct rbtnode node; int key, val; }; int paircmp(struct rbtnode *a, struct rbtnode *b){ struct pair *pa, *pb; int ret; pa = container_of(a, struct pair, node); pb = container_of(b, struct pair, node); if (pa->key > pb->key){ ret = CMP_GT; } else if (pa->key < pb->key){ ret = CMP_LT; } else { ret = CMP_EQ; } return ret; } void basic_test(void){ int fd, *arr; struct rbtree tree; struct pair sentinel, hint, *pair_arr; fd = open(TESTFNAME, O_RDONLY); arr = malloc(sizeof(uint32_t)*NINT32); read(fd, arr, sizeof(uint32_t)*NINT32); close(fd); pair_arr = calloc(NINT32, sizeof(struct pair)); rbtree_init(&tree, &sentinel.node, paircmp); for (int i = 0; i < NINT32; ++i){ struct pair *tmp = &pair_arr[i]; tmp->node.parent = NULL; tmp->node.left = NULL; tmp->node.right = NULL; tmp->key = i; rbtree_set(&tree, &tmp->node); } rbtree_validate(&tree); for (int i = 0; i < NINT32; ++i){ hint.key = i; assert(rbtree_get(&tree, &hint.node) != NULL); } rbtree_validate(&tree); for (int i = 0; i < NINT32; ++i){ struct pair *tmp = &pair_arr[i]; rbtree_delete(&tree, &tmp->node); } rbtree_validate(&tree); free(arr); free(pair_arr); return; } void torture_test(void){ return; } int main(void){ basic_test(); torture_test(); return 0; }
KIodine/naiveds
binheap/binheap.h
<gh_stars>1-10 #ifndef BINHEAP_H #define BINHEAP_H #include <stddef.h> /* A max heap/priority queue implementation. */ /* struct binheap binheap_alloc() binheap_free() binheap_insert() binheap_extract() binheap_chgprior() maxheapify() */ struct binheap { int *arr; int count, capacity; }; struct binheap *binheap_alloc(size_t cap); void binheap_free(struct binheap *heap); int binheap_insert(struct binheap *heap, int val); int binheap_extract(struct binheap *heap, int *res); void maxheapify(int *arr, int len); #endif
KIodine/naiveds
bstree/bstree.c
<gh_stars>1-10 #include "bstree.h" static struct bstnode *node_alloc(int key, int val){ struct bstnode *node = NULL; node = calloc(1, sizeof(struct bstnode)); node->key = key; node->val = val; return node; } static void tree_purge(struct bstnode* start){ if (start == NULL){ return; } tree_purge(start->left); tree_purge(start->right); free(start); return; } /* TODO modify these functions */ static struct bstnode **find_precedence(struct bstnode **start){ /* find the rightmost node of left subtree */ struct bstnode **can; can = &(*start)->left; if (*can == NULL){ return NULL; } for (;(*can)->right != NULL;){ can = &(*can)->right; } return can; } static struct bstnode **find_successor(struct bstnode **start){ /* find the leftmost node of right subtree */ struct bstnode **can; can = &(*start)->right; if (*can == NULL){ return NULL; } /* only modify parent if candidate exists */ for (;(*can)->left != NULL;){ can = &(*can)->left; } return can; } struct bstree *bstree_alloc(void){ struct bstree *tree = NULL; tree = calloc(1, sizeof(struct bstree)); return tree; } void bstree_purge(struct bstree *tree){ tree_purge(tree->root); tree->count = 0; return; } void bstree_free(struct bstree *tree){ tree_purge(tree->root); free(tree); return; } int bstree_set(struct bstree *tree, int key, int val){ struct bstnode *new = NULL, **indirect; /* `indirect` holds the pointer to either `left` or `right` of `struct bstnode`. the benefit of using `indirect` is that we can "directly" modify the field no matter what the form of the structure holding it, as long as all indirect pointer follow the same rule. */ /* (preserve for study purpose) if (tree->root == NULL){ new = node_alloc(key, val); tree->root = new; tree->count++; return BST_OK; } cur = tree->root; for (;;){ if (key == cur->key){ cur->val = val; break; } // decide which "way" we're modifying if (key < cur->key){ indirect = &cur->left; } else { indirect = &cur->right; } if (*indirect != NULL){ // if still branch to compare cur = *indirect; } else { // found a space new = node_alloc(key, val); // link the branch *indirect = new; tree->count++; break; } } */ indirect = &tree->root; for (;;){ // this field is containing NULL if ((*indirect) == NULL){ /* we've found an empty place, implies no corresponding key was found. */ new = node_alloc(key, val); *indirect = new; tree->count++; break; } /* assured (*indirect) is not NULL */ if (key < (*indirect)->key){ /* indirect points to the field instead */ indirect = &(*indirect)->left; } else if (key > (*indirect)->key){ indirect = &(*indirect)->right; } else { /* we're pointing is what we're looking for */ (*indirect)->val = val; break; } } return BST_OK; } int bstree_get(struct bstree *tree, int key, int *res){ struct bstnode *cur; cur = tree->root; for (;cur != NULL;){ if (cur->key == key){ *res = cur->val; break; } if (key < cur->key){ cur = cur->left; } else { cur = cur->right; } } if (cur == NULL){ return BST_NOELEM; } return BST_OK; } /* once find the correct entry: find precedence and its parent if precedence is not NULL copy key and val from precedence parend "adopt" left child of precedence free precedence set the parent's right to NULL else if successor is not NULL copy key and val from precedence parend "adopt" right child of successor free successor set the parent's left to NULL else (node is leaf node) free content of indirect (essentially `free(node->left)...`) set content of indirect to NULL */ /* Inspired by "Linus' good taste of coding". the use of `indirect` eliminates the need to check whether a node is the root or not, since it **"directly" points to the address of the field** (which its type is "pointer to struct", indirect is "pointer of pointer to struct"). A additional benefit is that `indirect` actually "stays" on its parent. if we know where the thing(pointer to struct) is, we can use it and even modify the field holds it. Or was it? */ int bstree_delete(struct bstree *tree, int key){ struct bstnode **indirect = &tree->root, **victim, *next, *hold; for (;*indirect != NULL;){ if ((*indirect)->key == key){ /* do delete stuff */ victim = find_precedence(indirect); // we can abuse pointer to make even shorter/cleaner code here. if (victim != NULL){ /* the "adopt", now victim is alone */ // abuse ver: *victim = (*victim)->left; // "unlinks" the node. next = (*victim)->left; break; } victim = find_successor(indirect); if (victim != NULL){ next = (*victim)->right; break; } /* it is a leaf node */ free(*indirect); /* set the branch to NULL */ *indirect = NULL; /* bypass the after loop condition check and victim-killing */ goto decr_count; } if (key < (*indirect)->key){ indirect = &(*indirect)->left; } else { indirect = &(*indirect)->right; } /* then continue */ } if (*indirect == NULL){ /* can't find the entry */ return BST_NOELEM; } /* we've completed the adopt, time to kill the victim */ (*indirect)->key = (*victim)->key; (*indirect)->val = (*victim)->val; hold = *victim; *victim = next; free(hold); decr_count: tree->count--; return BST_OK; }
KIodine/naiveds
hashtable-chain/test/main.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "hashmap.h" #define NL "\n" struct data { int value; struct map_node node; }; static void shuffle(int32_t *arr, size_t n){ unsigned int i_excg, tmp; srand(9997); // for test usage, this produces same psuedo random every time. for (size_t i = 0; i < n; ++i){ i_excg = rand(); i_excg %= n; tmp = arr[i]; arr[i] = arr[i_excg]; arr[i_excg] = tmp; } return; } static uint32_t data_hasher(struct map_node* mnode){ struct data *d; d = container_of(mnode, struct data, node); return d->value; } static int data_cmp(struct map_node *a, struct map_node *b){ struct data *da, *db; da = container_of(a, struct data, node); db = container_of(b, struct data, node); return (da->value == db->value); } static int basic_test(void){ struct data *data_arr, hint, *res; struct map *datamap; struct map_node *tmp_node; const size_t n_data = 197; int32_t *int_arr; datamap = map_alloc(256, data_hasher, data_cmp); int_arr = malloc(sizeof(int32_t) * n_data); for (unsigned int i = 0; i < n_data; ++i){ int_arr[i] = i; } shuffle(int_arr, n_data); data_arr = calloc(n_data, sizeof(struct data)); for (unsigned int i = 0; i < n_data; ++i){ data_arr[i].value = int_arr[i]; } memset(&hint, 0, sizeof(struct data)); printf("test insert"NL); for (unsigned int i = 0; i < n_data; ++i){ map_insert(datamap, &data_arr[i].node); } printf("test get"NL); for (unsigned int i = 0; i < n_data; ++i){ hint.value = int_arr[i]; tmp_node = map_get(datamap, &hint.node); assert(tmp_node != NULL); res = container_of(tmp_node, struct data, node); assert(res->value == int_arr[i]); //printf("res: %d"NL, res->value); } printf("test delete"NL); for (unsigned int i = 0; i < n_data; ++i){ map_delete(datamap, &data_arr[i].node); } printf("test done"NL); free(data_arr); free(int_arr); map_free(datamap); printf("free completed"NL); return 0; } int main(void){ setbuf(stdout, NULL); basic_test(); return 0; }
KIodine/naiveds
doubly-linked-list/dllist.c
#include "dllist.h" static struct dllnode *node_alloc(int val){ struct dllnode *node; node = calloc(1, sizeof(struct dllnode)); node->val = val; return node; } static void node_purge(struct dllnode *node){ struct dllnode *hold; for (struct dllnode *n = node->next; n != node;){ hold = n; n = n->next; free(hold); } node->next = node; node->prev = node; return; } void dll_purge(struct dllist *list){ list->count = 0; node_purge(&list->first); return; } struct dllist *dll_alloc(void){ struct dllist *list; struct dllnode *sentinel; list = calloc(1, sizeof(struct dllist)); sentinel = &list->first; sentinel->next = sentinel; sentinel->prev = sentinel; // the first node is used as sentinel node and thus // holds no data. return list; } void dll_free(struct dllist *list){ list->count = 0; node_purge(&list->first); free(list); return; } int dll_push(struct dllist *list, int val){ struct dllnode *sentinel = &list->first, *old_next, *new; old_next = sentinel->next; new = node_alloc(val); new->next = old_next; new->prev = sentinel; old_next->prev = new; sentinel->next = new; return DLL_OK; } int dll_pop(struct dllist *list, int *res){ struct dllnode *sentinel = &list->first, *hold; if (sentinel->next == sentinel){ return DLL_NOELEM; } hold = sentinel->next; sentinel->next = hold->next; hold->next->prev = sentinel; *res = hold->val; free(hold); return DLL_OK; } int dll_append(struct dllist *list, int val){ struct dllnode *sentinel = &list->first, *new, *old_prev; old_prev = sentinel->prev; new = node_alloc(val); new->next = sentinel; new->prev = old_prev; old_prev->next = new; sentinel->prev = new; return DLL_OK; } int dll_get(struct dllist *list, int *res){ struct dllnode *sentinel = &list->first, *hold; if (sentinel->prev == sentinel){ return DLL_NOELEM; } hold = sentinel->prev; sentinel->prev = hold->prev; hold->prev->next = sentinel; *res = hold->val; free(hold); return DLL_OK; } int dll_delete(struct dllist *list, int val){ struct dllnode* sentinel = &list->first, *cur, *prev; for (cur = sentinel->next; cur != sentinel; cur = cur->next){ if (cur->val == val){ prev = cur->prev; prev->next = cur->next; cur->next->prev = prev; free(cur); break; } } return cur != sentinel? DLL_OK: DLL_NOELEM; }
KIodine/naiveds
intrusive-avltree/test/main.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <assert.h> #include <fcntl.h> #include "avltree.h" #include "avldbg.h" #define NL "\n" #define NNUMS 4096 struct pair { struct avlnode node; int key; }; static int pair_cmp(struct avlnode const *a, struct avlnode const *b){ struct pair *pa, *pb; int cmpres; pa = container_of(a, struct pair, node); pb = container_of(b, struct pair, node); if (pa->key > pb->key){ cmpres = NODE_GT; } else if (pa->key < pb->key){ cmpres = NODE_LT; } else { cmpres = NODE_EQ; } return cmpres; } static void shuffle(int32_t *arr, size_t n){ unsigned int i_excg, tmp; srand(9997); // for test usage, this produces same psuedo random every time. for (size_t i = 0; i < n; ++i){ i_excg = rand(); i_excg %= n; tmp = arr[i]; arr[i] = arr[i_excg]; arr[i_excg] = tmp; } return; } static void basic_test(void){ avl_tree_decl(tree, pair_cmp); int const N_NODES = 1000000; int *narr; struct pair *parr, *tmp_pair, hint_pair; struct avlnode *tmp_node; memset(&hint_pair.node, 0, sizeof(struct avlnode)); parr = calloc(N_NODES, sizeof(struct pair)); narr = malloc(N_NODES*sizeof(int)); for (int i = 0; i < N_NODES; ++i){ narr[i] = i; } shuffle(narr, N_NODES); printf("basic insert..."); for (int i = 0; i < N_NODES; ++i){ parr[i].key = narr[i]; tmp_node = avl_insert(&tree, &parr[i].node); assert(tmp_node == &parr[i].node); } avl_validate(&tree); printf("ok"NL); printf("basic get..."); for (int i = 0; i < N_NODES; ++i){ hint_pair.key = narr[i]; tmp_node = avl_get(&tree, &hint_pair.node); assert(tmp_node != NULL); tmp_pair = container_of(tmp_node, struct pair, node); assert(tmp_pair->key == narr[i]); } printf("ok"NL); printf("basic delete..."); for (int i = 500; i < 6000; ++i){ tmp_pair = &parr[i]; tmp_node = avl_delete(&tree, &tmp_pair->node); assert(tmp_node == &tmp_pair->node); } avl_validate(&tree); printf("ok"NL); printf("basic test done"NL); free(parr); free(narr); return; } static void torture_test(void){ avl_tree_decl(tree, pair_cmp); int32_t *narr; struct pair *parr, *tmp_pair, hint_pair; struct avlnode *tmp_node; parr = calloc(NNUMS, sizeof(struct pair)); narr = malloc(sizeof(int32_t)*NNUMS); for (int i = 0; i < NNUMS; ++i){ narr[i] = i; } shuffle(narr, NNUMS); printf("torture insert..."); for (int i = 0; i < NNUMS; ++i){ parr[i].key = narr[i]; tmp_node = avl_insert(&tree, &parr[i].node); //assert(ret == 0); } avl_validate(&tree); printf("ok"NL); printf("torture get..."); for (int i = 0; i < NNUMS; ++i){ hint_pair.key = narr[i]; tmp_node = avl_get(&tree, &hint_pair.node); assert(tmp_node != NULL); } printf("ok"NL); printf("torture delete..."); for (int i = 25; i < 3100; ++i){ tmp_pair = &parr[i]; tmp_node = avl_delete(&tree, &tmp_pair->node); assert(tmp_node == &tmp_pair->node); } avl_validate(&tree); printf("ok"NL); free(narr); free(parr); return; } int main(void){ // forces stdout flush setbuf(stdout, NULL); basic_test(); torture_test(); return 0; }
KIodine/naiveds
skiplist/test/slist_basic.c
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <time.h> #include "skiplist.h" static int shuffle_int(int arr[], int n); static int basic_test(void); static int main_test(int test_nodes); //static int const test_nodes = 2600000; static int const test_scales[] = { /* 16, */ 100000, 200000, 400000, 800000, 1600000, /* */ }; int main(int argc, char **argv){ srand(1997); //setbuf(stdout, NULL); // --- basic_test(); printf("--- Basic test done ---\n"); for (unsigned int i = 0; i < sizeof(test_scales)/sizeof(test_scales[0]); i++){ printf("> Testing on %d nodes.\n", test_scales[i]); main_test(test_scales[i]); } printf("--- Main test done ---\n"); return 0; } static int shuffle_int(int arr[], int n){ for (int i = 0; i < n; i++){ int tmp, idx = rand()%n; tmp = arr[i]; arr[i] = arr[idx]; arr[idx] = tmp; } return 0; } static int basic_test(void){ int ret = 0, res = 0; struct skiplist *slist = NULL; slist = skiplist_alloc(); ret = skiplist_get(slist, -1, &res); assert(ret == -1); ret = skiplist_set(slist, 0, -1); assert(ret == 0); ret = skiplist_set(slist, 0, -2); assert(ret == -1); ret = skiplist_get(slist, 0, &res); assert(ret == 0); assert(res == -1); ret = skiplist_del(slist, 0); assert(ret == 0); ret = skiplist_del(slist, 0); assert(ret == -1); skiplist_free(slist); slist = NULL; return 0; } static int main_test(int test_nodes){ int ret, res, *arr; struct timespec start, dt; long long steps; double ns; struct skiplist *slist = NULL; arr = malloc(test_nodes*sizeof(int)); for (int i = 0; i < test_nodes; i++){ arr[i] = i; } shuffle_int(arr, test_nodes); slist = skiplist_alloc(); /* Setup nodes. */ printf("Setup nodes..."); clock_gettime(CLOCK_MONOTONIC, &start); for (int i = 0; i < test_nodes; ++i){ ret = skiplist_set(slist, arr[i], i); assert(ret == 0); } clock_gettime(CLOCK_MONOTONIC, &dt); if (dt.tv_nsec < start.tv_nsec){ dt.tv_sec -= 1; dt.tv_nsec += 1000000000; } dt.tv_nsec -= start.tv_nsec; dt.tv_sec -= start.tv_sec; ns = (double)dt.tv_nsec + ((double)dt.tv_sec*1e9); ns /= (double)test_nodes; printf(" %.3f ns/op\n", ns); /* Ensure all nodes are inserted and properly set. */ slist->search_steps = 0; printf("fetching nodes..."); clock_gettime(CLOCK_MONOTONIC, &start); for (int i = 0; i < test_nodes; ++i){ ret = skiplist_get(slist, arr[i], &res); assert(ret == 0); //assert(res == i*2); } clock_gettime(CLOCK_MONOTONIC, &dt); if (dt.tv_nsec < start.tv_nsec){ dt.tv_sec -= 1; dt.tv_nsec += 1000000000; } dt.tv_nsec -= start.tv_nsec; dt.tv_sec -= start.tv_sec; ns = (double)dt.tv_nsec + ((double)dt.tv_sec*1e9); ns /= (double)test_nodes; printf(" %.3f ns/op\n", ns); steps = slist->search_steps/test_nodes; /* Delete some nodes. */ printf("delete 75%% nodes..."); clock_gettime(CLOCK_MONOTONIC, &start); for (int i = test_nodes/4; i < test_nodes; ++i){ ret = skiplist_del(slist, arr[i]); assert(ret == 0); } clock_gettime(CLOCK_MONOTONIC, &dt); if (dt.tv_nsec < start.tv_nsec){ dt.tv_sec -= 1; dt.tv_nsec += 1000000000; } dt.tv_nsec -= start.tv_nsec; dt.tv_sec -= start.tv_sec; ns = (double)dt.tv_nsec + ((double)dt.tv_sec*1e9); ns /= (double)(test_nodes-test_nodes/4); printf(" %.3f ns/op\n", ns); /* Ensure those deleted are unreachable. */ printf("Ensure nodes are deleted..."); clock_gettime(CLOCK_MONOTONIC, &start); for (int i = test_nodes/4; i < test_nodes; ++i){ ret = skiplist_get(slist, arr[i], &res); assert(ret == -1); } clock_gettime(CLOCK_MONOTONIC, &dt); if (dt.tv_nsec < start.tv_nsec){ dt.tv_sec -= 1; dt.tv_nsec += 1000000000; } dt.tv_nsec -= start.tv_nsec; dt.tv_sec -= start.tv_sec; ns = (double)dt.tv_nsec + ((double)dt.tv_sec*1e9); ns /= (double)test_nodes; printf(" %.3f ns/op\n", ns); printf("Dist of levels:\n"); for (int i = 0; i < SKIPLIST_MAX_LEVEL; i++){ printf("[%2d]=%d\n", i, slist->dist[i]); } printf("Avg search steps: %lld\n", steps); skiplist_free(slist); slist = NULL; free(arr); arr = NULL; return 0; }
KIodine/naiveds
threaded-avltree/src/avltree.c
<gh_stars>1-10 #include "avltree.h" #include "avlinc.h" static inline int max(int a, int b); static inline int min(int a, int b); static inline void node_clear(struct avlnode *node); static struct avlnode *node_min(struct avlnode *node); static void left_rotate(struct avltree *tree, struct avlnode *a); static void right_rotate(struct avltree *tree, struct avlnode *a); static inline int max(int a, int b){ return (a > b)? a: b; } static inline int min(int a, int b){ return (b > a)? a: b; } static inline void node_clear(struct avlnode *node){ memset(node, 0, sizeof(struct avlnode)); return; } static struct avlnode *node_min(struct avlnode *node){ if (node == NULL){ return NULL; } for (;node->child[CLD_L] != NULL;){ node = node->child[CLD_L]; } return node; } static void left_rotate(struct avltree *tree, struct avlnode *a){ struct avlnode *b, *beta, *parent, **rootp; b = a->child[CLD_R]; beta = b->child[CLD_L]; parent = a->parent; rootp = &tree->root; a->child[CLD_R] = beta; if (beta != NULL){ beta->parent = a; } if (parent != NULL){ if (a == parent->child[CLD_L]){ parent->child[CLD_L] = b; } else { parent->child[CLD_R] = b; } } else { *rootp = b; } b->parent = parent; b->child[CLD_L] = a; a->parent = b; a->factor = a->factor - max(b->factor, 0) - 1; b->factor = b->factor + min(a->factor, 0) - 1; return; } static void right_rotate(struct avltree *tree, struct avlnode *a){ struct avlnode *b, *beta, *parent, **rootp; b = a->child[CLD_L]; beta = b->child[CLD_R]; parent = a->parent; rootp = &tree->root; a->child[CLD_L] = beta; if (beta != NULL){ beta->parent = a; } if (parent != NULL){ if (a == parent->child[CLD_L]){ parent->child[CLD_L] = b; } else { parent->child[CLD_R] = b; } } else { *rootp = b; } b->parent = parent; b->child[CLD_R] = a; a->parent = b; a->factor = a->factor - min(b->factor, 0) + 1; b->factor = b->factor + max(a->factor, 0) + 1; return; } struct avlnode *avl_insert(struct avltree *tree, struct avlnode *node){ int cmpres; struct avlnode **tmp, **rootp, *fix = NULL; tmp = &tree->root; rootp = tmp; assert(node->factor == 0); for (;(*tmp) != NULL;){ cmpres = tree->cmp(node, (*tmp)); fix = *tmp; if (cmpres < 0){ tmp = &(*tmp)->child[CLD_L]; } else if (cmpres > 0){ tmp = &(*tmp)->child[CLD_R]; } else { break; } } if ((*tmp) != NULL){ // place have been occupied return *tmp; } /* Do tree insert. */ *tmp = node; if ((*tmp) == *rootp){ // special case: insert at root list_append(&tree->head, &node->node); return node; } node->parent = fix; /* Do list insert. */ if (node == fix->child[CLD_L]){ list_append(&fix->node, &node->node); } else { list_push(&fix->node, &node->node); } // do fix struct avlnode *child = node; int is_same_dir, tmp_factor; for (;fix != NULL;){ tmp_factor = fix->factor; if (child == fix->child[CLD_L]){ tmp_factor -= 1; } else { tmp_factor += 1; } fix->factor = tmp_factor; if (tmp_factor == 0){ // the insertion balances the tree, bail out goto fix_done; } assert(tmp_factor != 0); if (abs(tmp_factor) < 2){ // step upward child = fix; fix = fix->parent; continue; } assert(tmp_factor != 0 && abs(tmp_factor) == 2); if (fix->factor < 0){ child = fix->child[CLD_L]; } else { child = fix->child[CLD_R]; } is_same_dir = (child->factor < 0) == (fix->factor < 0); if (child->factor != 0 && !is_same_dir){ // inbalabce and not the same direction as parent if (child->factor < 0){ // RL case right_rotate(tree, child); } else { // LR case left_rotate(tree, child); } // after rotation, node has descended for one level child = child->parent; } if (fix->factor < 0){ right_rotate(tree, fix); } else { left_rotate(tree, fix); } // it is guarenteed after one fix, the tree must be a valid AVL // tree (but can update factor up to log n). break; } fix_done: return node; } struct avlnode *avl_get(struct avltree *tree, struct avlnode *hint){ int cmpres; struct avlnode *res = tree->root; for (;res != NULL;){ cmpres = tree->cmp(hint, res); if (cmpres < 0){ res = res->child[CLD_L]; } else if (cmpres > 0){ res = res->child[CLD_R]; } else { break; } } return res; } struct avlnode *avl_delete(struct avltree *tree, struct avlnode *node){ struct avlnode *tmp, *parent, *fix; parent = node->parent; /* Simply remove it. */ list_delete(&node->node); if (!node->child[CLD_L] || !node->child[CLD_R]){ // if either side is NULL tmp = node->child[CLD_R]? node->child[CLD_R]: node->child[CLD_L]; // `tmp` is the non-NULL side (or not if both are NULL) // In this case, we just link the `tmp` with `parent` if (tmp != NULL){ fix = tmp; } else { fix = parent; if (node == fix->child[CLD_L]){ fix->factor++; } else { fix->factor--; } } } else { // 2 child case, tmp is guarenteed to be non-NULL tmp = node_min(node->child[CLD_R]); assert(tmp->child[CLD_L] == NULL); if (tmp != node->child[CLD_R]){ // is not direct child, we have to link the "orphan" tmp->factor = node->factor; fix = tmp->parent; fix->factor += 1; tmp->parent->child[CLD_L] = tmp->child[CLD_R]; if (tmp->child[CLD_R] != NULL){ tmp->child[CLD_R]->parent = tmp->parent; } tmp->child[CLD_R] = node->child[CLD_R]; node->child[CLD_R]->parent = tmp; } else { // is direct child if (tmp->child[CLD_R] != NULL){ fix = tmp->child[CLD_R]; fix->factor = tmp->factor; } else { fix = tmp; } tmp->factor = node->factor; fix->factor -= 1; } tmp->child[CLD_L] = node->child[CLD_L]; node->child[CLD_L]->parent = tmp; } // link parent and tmp if (tmp != NULL){ // could from one child case tmp->parent = parent; } if (parent != NULL){ if (node == parent->child[CLD_L]){ parent->child[CLD_L] = tmp; } else { parent->child[CLD_R] = tmp; } } else { tree->root = tmp; } // do fix if `fix->factor == 0` // keep update height until one of: // - root is reached // - proper fix is applied // - the fix node just become inbalance/skew // (just handled a single-heavy case) if (fix->factor != 0 && abs(fix->factor) < 2){ goto delete_done; } struct avlnode *child = NULL; int is_same_dir, is_child_rotate; // child may be NULL, so we mix the first factor update in previous // code sections for (;fix != NULL;){ is_child_rotate = 0; if (fix->factor == 0){ goto update; } // factor is non-zero if (abs(fix->factor) < 2){ break; } // |factor| is ge 2 and non-zero assert(fix->factor != 0); assert(abs(fix->factor) == 2); if (fix->factor > 0){ child = fix->child[CLD_R]; } else { child = fix->child[CLD_L]; } // double heavy or single heavy assert(child != NULL); is_same_dir = (fix->factor > 0) == (child->factor > 0); is_child_rotate = (child->factor != 0); // note that `is_same_dir` doesn't cover the case // when `child->factor == 0`. if (!is_same_dir && is_child_rotate){ if (child->factor > 0){ left_rotate(tree, child); } else { right_rotate(tree, child); } // child have descended for one level, fix that child = child->parent; } if (fix->factor > 0){ left_rotate(tree, fix); } else { right_rotate(tree, fix); } // since fix descended for one level, fix that fix = fix->parent; // In previous version, the `is_child_rotate` flag erroneously // let the `update` case breaks. if (!is_child_rotate){ // fixed pure L or R case break; } update: if (fix->parent == NULL){ // fix is root break; } // after LL LR RL RR fix, the height is descended, change // propagates. child = fix; fix = fix->parent; if (child == fix->child[CLD_L]){ fix->factor++; } else { fix->factor--; } } delete_done: /* clear attributes of node. */ node_clear(node); return node; } struct avlnode *avl_replace( struct avltree *tree, struct avlnode *node, struct avlnode *sub ){ struct avlnode *par; struct list *prev, *next; int dir; node->child[CLD_L] = sub->child[CLD_L]; node->child[CLD_R] = sub->child[CLD_R]; node->factor = sub->factor; node->parent = sub->parent; /* link parent and children. */ par = node->parent; if (node == tree->root){ tree->root = node; } else { dir = (sub == par->child[CLD_L]); par->child[dir] = node; } if (node->child[CLD_L] != NULL){ node->child[CLD_L]->parent = node; } if (node->child[CLD_R] != NULL){ node->child[CLD_R]->parent = node; } prev = sub->node.prev; next = sub->node.next; node->node.prev = prev; node->node.next = next; prev->next = &node->node; next->prev = &node->node; /* Remove any identity of subject. */ node_clear(sub); return sub; }
KIodine/naiveds
intrusive-avltree/include/avltree.h
#ifndef AVLTREE_H #define AVLTREE_H #include <string.h> #include <stddef.h> // copy from <linux/kernel.h> and strip debug stuffs. #define container_of(ptr, type, member) ({ \ void *__mptr = (void *)(ptr); \ ((type *)(__mptr - offsetof(type, member))); }) struct avlnode; /* eval: a <cmp op> b ret val <--- -1| 0 | 1 ---> (int) meaning <--- LT|EQL|GT ---> ex: cmp(a, b) -> -1 equal to a < b */ typedef int (*avl_cmp_t)(struct avlnode const *a, struct avlnode const *b); struct avlnode { struct avlnode *child[2], *parent; int factor; }; struct avltree { struct avlnode *root; int count; avl_cmp_t cmp; }; enum { // type generic comp res NODE_LT = -1, NODE_EQ = 0, NODE_GT = 1, // access child pointer CLD_L = 0, CLD_R = 1, }; #define _STMT(stmt) \ do { \ (stmt) \ } while (0); #define avl_tree_decl(sym, comparator) \ struct avltree (sym) = { \ .root = NULL, \ .cmp = &(comparator), \ .count = 0, \ } #define avl_tree_init(tree, comparator) \ _STMT( \ (tree)->root = NULL; \ (tree)->cmp = &(cmparator); \ (tree)->count = 0; \ ) #define avl_node_init(node) \ _STMT( \ memset((node), 0, sizeof(struct avlnode));\ ) struct avlnode *avl_insert(struct avltree *tree, struct avlnode *node); struct avlnode *avl_get(struct avltree *tree, struct avlnode *hint); struct avlnode *avl_delete(struct avltree *tree, struct avlnode *node); struct avlnode *avl_replace( struct avltree *tree, struct avlnode *node, struct avlnode *sub ); // debug use void avl_print(struct avltree *tree); void avl_validate(struct avltree *tree); #endif /* AVLTREE_H */
KIodine/naiveds
threaded-avltree/src/list.c
#include "list.h" /* insert after */ void list_push(struct list *head, struct list *node){ struct list *hnxt; hnxt = head->next; node->next = hnxt; node->prev = head; hnxt->prev = node; head->next = node; return; } struct list *list_pop(struct list *head){ struct list *tmp, *tnxt; if (list_is_empty(head)) return NULL; tmp = head->next; tnxt = tmp->next; head->next = tnxt; tnxt->prev = head; tmp->next = tmp; tmp->prev = tmp; return tmp; } /* insert before */ void list_append(struct list *head, struct list *node){ struct list *hprv; hprv = head->prev; node->prev = hprv; node->next = head; hprv->next = node; head->prev = node; return; } struct list *list_get(struct list *head){ struct list *tmp, *tprv; if (list_is_empty(head)) return NULL; tmp = head->prev; tprv = tmp->prev; head->prev = tprv; tprv->next = head; tmp->next = tmp; tmp->prev = tmp; return tmp; } void list_delete(struct list *node){ struct list *nprv, *nnxt; nprv = node->prev; nnxt = node->next; nprv->next = nnxt; nnxt->prev = nprv; node->prev = node->next = node; return; }
KIodine/naiveds
skiplist/src/skiplist.c
#include "skiplist.h" #include "slist_internal.h" static int generate_level(void); static struct skiplist_node *slist_node_alloc(int level); static struct skiplist_node *skiplist_get_ex( struct skiplist *slist, int key, struct skiplist_link *prevs[SKIPLIST_MAX_LEVEL] ); //static void slist_node_free(struct skiplist_node *snode); /* Just use normal `free` to dealloc node. */ static int generate_level(void){ int level = 0; for (;level < SKIPLIST_MAX_LEVEL;){ /* approximately 1/4 ~= 0.25 */ // or better implementation? if (rand() < RAND_MAX/2 && level < (SKIPLIST_MAX_LEVEL-1)){ level++; continue; } break; } assert(level < SKIPLIST_MAX_LEVEL); return level; } static struct skiplist_node *slist_node_alloc(int level){ struct skiplist_node *snode = NULL; if (level < 0){ return NULL; } snode = calloc( 1, sizeof(struct skiplist_node)+sizeof(struct skiplist_link)*(level+1) ); if (snode == NULL){ return NULL; } snode->level = level; return snode; } struct skiplist *skiplist_alloc(void){ struct skiplist *slist = NULL; struct skiplist_node *header = NULL; slist = calloc(1, sizeof(struct skiplist)); if (slist == NULL){ goto slist_fail; } header = slist_node_alloc(SKIPLIST_MAX_LEVEL); if (header == NULL){ goto header_fail; } slist->header = header; return slist; header_fail: free(slist); slist_fail: return NULL; } void skiplist_free(struct skiplist *slist){ struct skiplist_node *cur = NULL, *nxt = NULL; /* The lowest level consists all links. */ cur = slist->header->links[0].next; for (;cur != NULL;){ nxt = cur->links[0].next; free(cur); cur = nxt; } free(slist->header); free(slist); return; } /* This is the fundamental of all skiplist operation, especially its argument `pprevs`, records the place a node (could) at. Return value indicates whether the node exists or not. */ static struct skiplist_node *skiplist_get_ex( struct skiplist *slist, int key, struct skiplist_link *prevs[SKIPLIST_MAX_LEVEL] ){ // --- struct skiplist_node *nxt, *found = NULL; struct skiplist_link *cur; int cur_lvl = SKIPLIST_MAX_LEVEL-1; cur = slist->header->links; int s = 0; for (;cur_lvl >= 0; cur_lvl--){ nxt = cur[cur_lvl].next; /* Tree-like structures are less able to utilize cache. */ for (;nxt != NULL && nxt->key < key;){ s++; cur = nxt->links; nxt = cur[cur_lvl].next; } /* record `cur` as prev and down the level. */ prevs[cur_lvl] = cur; } if (nxt != NULL && nxt->key == key){ found = nxt; } slist->search_steps += s; return found; } int skiplist_get(struct skiplist *slist, int key, int *res){ int found = -1; struct skiplist_link *prevs[SKIPLIST_MAX_LEVEL]; struct skiplist_node *target = NULL; target = skiplist_get_ex(slist, key, prevs); if (target != NULL){ *res = target->val; found = 0; } return found; } int skiplist_set(struct skiplist *slist, int key, int val){ int level; struct skiplist_link *prevs[SKIPLIST_MAX_LEVEL]; struct skiplist_node *node = NULL; node = skiplist_get_ex(slist, key, prevs); if (node != NULL){ /* > Maybe do update. */ return -1; } level = generate_level(); assert(level < SKIPLIST_MAX_LEVEL); node = slist_node_alloc(level); if (node == NULL){ return -1; } /* debug */ slist->dist[level] += 1; if (level > slist->current_max_level){ /* Don't forget to update! */ slist->current_max_level = level; } assert(node->level == level); node->key = key; node->val = val; struct skiplist_node *nxt; struct skiplist_link *prv; for (int i = 0; i < (level+1); i++){ prv = prevs[i]; // The `links` of prev node. nxt = prv[i].next; node->links[i].next = nxt; prv[i].next = node; } return 0; } int skiplist_del(struct skiplist *slist, int key){ struct skiplist_node *node = NULL; struct skiplist_link *prevs[SKIPLIST_MAX_LEVEL]; node = skiplist_get_ex(slist, key, prevs); if (node == NULL){ return -1; // ??? } struct skiplist_node *nxt; struct skiplist_link *prv; for (int i = 0; i < (node->level+1); ++i){ prv = prevs[i]; nxt = node->links[i].next; prv[i].next = nxt; } free(node); return 0; }
KIodine/naiveds
hashtable-chain/src/hashmap.c
<reponame>KIodine/naiveds #include "hashmap.h" #define NL "\n" #define debug_print(fmt, ...) printf("[hashmap]" fmt, __VA_ARGS__); #define debug_msg(s) printf("[hashmap]" s); static void map_init(struct map *m, unsigned int size_hint, obj_hasher hash, obj_cmp cmp); static struct map_node **map_find_slot(struct map_node **bucket, struct map_node *mnode, uint32_t hashval, obj_cmp cmp); static int map_is_need_grow(struct map *map); static void map_resize(struct map *map); static inline unsigned int round_up_pow_2(unsigned int v); static inline void node_insert(struct map_node **slot, struct map_node *ins); static inline unsigned int round_up_pow_2(unsigned int v){ /* * fill bits lower than the leftmost bit. * the decrement and increment prevents numbers already are * power or 2 doubles. */ v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } struct map *map_alloc(unsigned int size_hint, obj_hasher hash, obj_cmp cmp){ struct map *m; m = malloc(sizeof(struct map)); map_init(m, size_hint, hash, cmp); return m; } static void map_init( struct map *m, unsigned int size_hint, obj_hasher hash, obj_cmp cmp ){ unsigned int size, thres; size = round_up_pow_2(size_hint); thres = ((size + 1)*3)/4; /* 75% full */ debug_print("rounding %u to %u"NL, size_hint, size); debug_print("threshold is %u"NL, thres); m->bucket = calloc(size, sizeof(struct map_node*)); m->hasher = hash; m->cmp = cmp; m->count = 0; m->capacity = size; m->resize_thres = thres; return; } static int map_is_need_grow(struct map *m){ return m->count >= m->resize_thres; } void map_free(struct map *m){ free(m->bucket); free(m); return; } static void map_resize(struct map *m){ struct map_node **new_bkt, **old_bkt, **tmp_bkt, **slot, *tmp_nd, *hold; unsigned int new_size, old_size, thres; uint32_t hashval; old_size = m->capacity; new_size = m->capacity << 1; thres = ((new_size + 1)*3)/4; new_bkt = calloc(new_size, sizeof(struct map_node*)); old_bkt = m->bucket; debug_print("resizing map to %u (was %u)"NL, new_size, old_size); debug_print("new threshold is %u"NL, thres); debug_msg(">>>start resize"NL); for (unsigned int i = 0; i < old_size; ++i){ tmp_nd = old_bkt[i]; for (;tmp_nd != NULL;){ hold = tmp_nd->next; hashval = tmp_nd->hashval; tmp_bkt = &new_bkt[hashval%new_size]; /* clean the links */ tmp_nd->next = NULL; tmp_nd->pprev = NULL; slot = map_find_slot(tmp_bkt, tmp_nd, hashval, m->cmp); assert(*slot == NULL); node_insert(slot, tmp_nd); tmp_nd = hold; } } m->bucket = new_bkt; m->capacity = new_size; m->resize_thres = thres; free(old_bkt); /* alloc new bucket for every node in old bucket: get new bucket index find slot for new bucket insert node into slot free old bucket update size update threshold */ debug_print("<<<resize to %u completed"NL, new_size); return; } static struct map_node **map_find_slot( struct map_node **bucket, struct map_node *mnode, uint32_t hashval, obj_cmp cmp ){ struct map_node **tmp = NULL; /* proceed until: 1) no next node 2) current node equals mnode(hint) */ tmp = bucket; for (;(*tmp) != NULL;){ // Hash value might be the same on different objects, but // if hash value is not the same, the two objects must be // different. This will provide a much lower cost comparing // doing full comparison each time. if ((*tmp)->hashval == hashval){ if (cmp(*tmp, mnode) != 0){ break; } } debug_print("collision detected, val=%u"NL, hashval); tmp = &(*tmp)->next; } return tmp; } static inline void node_insert(struct map_node **slot, struct map_node *ins){ *slot = ins; ins->pprev = slot; return; } int map_insert(struct map *m, struct map_node *mnode){ uint32_t hashval = 0; int is_existed = 0; struct map_node **bucket; struct map_node **tmp_nd; hashval = m->hasher(mnode); mnode->hashval = hashval; bucket = &m->bucket[hashval%m->capacity]; tmp_nd = map_find_slot(bucket, mnode, hashval, m->cmp); is_existed = ((*tmp_nd != NULL)); if (!is_existed){ node_insert(tmp_nd, mnode); m->count++; /* grow map if need */ if (map_is_need_grow(m)){ debug_print("count %u >= thres %u, now grow"NL, m->count, m->resize_thres); map_resize(m); } } return -is_existed; } struct map_node *map_get(struct map *m, struct map_node *hint){ uint32_t hashval = 0; struct map_node **bucket; struct map_node **tmp_nd; hashval = m->hasher(hint); bucket = &m->bucket[hashval%m->capacity]; tmp_nd = map_find_slot(bucket, hint, hashval, m->cmp); return *tmp_nd; } /* delete: remove node */ int map_delete(struct map *m, struct map_node *mnode){ *mnode->pprev = mnode->next; mnode->next = NULL; mnode->pprev = NULL; m->count--; return 0; }
KIodine/naiveds
skiplist/include/skiplist.h
<reponame>KIodine/naiveds<gh_stars>1-10 #ifndef SKIPLIST_H #define SKIPLIST_H #define SKIPLIST_MAX_LEVEL 24 /* > Hide definition completly? */ struct skiplist_link { struct skiplist_node *next; }; /* TODO: Move `links` to head and alloc separately. */ struct skiplist_node { //struct skiplist_link *links; // flex array member. int key, val; int level; struct skiplist_link links[]; // flex array member. }; struct skiplist { int current_max_level; struct skiplist_node *header; /* debug */ int dist[SKIPLIST_MAX_LEVEL]; long long search_steps; }; struct skiplist *skiplist_alloc(void); void skiplist_free(struct skiplist *slist); int skiplist_get(struct skiplist *slist, int key, int *res); int skiplist_set(struct skiplist *slist, int key, int val); int skiplist_del(struct skiplist *slist, int key); /* static int skiplist_get_ex( struct skiplist *slist, int key, struct skiplist *prevs[SKIPLIST_NAX_LEVEL] ); // This is the bottom layer of all skiplist API. */ #endif
KIodine/naiveds
intrusive-list/test.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include <unistd.h> #include <fcntl.h> #include "list.h" #define NL "\n" #define NINT32 1000000 struct testnode { int val; struct list node; }; void basic_test(void){ int fd; uint32_t *arr; uint32_t readsz = sizeof(uint32_t)*NINT32; struct testnode *nodearr; list_decl(head); fd = open("./testints.bin", O_RDONLY); arr = malloc(readsz); nodearr = malloc(sizeof(struct testnode)*NINT32); for (int i = 0; i < NINT32; ++i){ nodearr[i].val = arr[i]; } read(fd, arr, readsz); close(fd); for (int i = 0; i < NINT32; ++i){ list_push(&head, &nodearr[i].node); } for (int i = 0; i < NINT32; ++i){ assert(list_pop(&head) != NULL); } assert(list_is_empty(&head)); for (int i = 0; i < NINT32; ++i){ list_append(&head, &nodearr[i].node); } for (int i = 0; i < NINT32; ++i){ assert(list_get(&head) != NULL); } assert(list_is_empty(&head)); for (int i = 0; i < NINT32; ++i){ list_push(&head, &nodearr[i].node); } for (int i = 0; i <NINT32; ++i){ list_delete(&nodearr[i].node); } assert(list_is_empty(&head)); free(nodearr); free(arr); return; } int main(void){ return 0; }
KIodine/naiveds
threaded-avltree/include/avlinc.h
#ifndef AVLINC_H #define AVLINC_H /* Headers for internal usage. */ #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stddef.h> #endif /* AVLINC_H */
KIodine/naiveds
avltree/avltree.c
<filename>avltree/avltree.c<gh_stars>1-10 #include "avltree.h" static struct avlnode *node_alloc(int key, int val); static void node_free(struct avlnode *node); static int node_insert(struct avlnode **node, int key, int val); static int node_delete(struct avlnode **node, int key); static void node_fix(struct avlnode **node); static void node_validate(struct avlnode *node); static inline int get_height(struct avlnode *node); static inline void update_height(struct avlnode *node); static inline int max(int a, int b); static void left_rotate(struct avlnode **a); static void right_rotate(struct avlnode **a); static struct avlnode **node_min(struct avlnode **node); static void node_trav(struct avlnode *node, int depth); // static void AVLize(struct avlnode **node); static inline int get_height(struct avlnode *node){ return (node == NULL)? -1: node->height; } static inline int max(int a, int b){ return a > b? a: b; } static inline void update_height(struct avlnode *node){ int lh, rh; lh = get_height(node->child[CLD_L]); rh = get_height(node->child[CLD_R]); node->height = max(lh, rh) + 1; return; } static void node_fix(struct avlnode **node){ int lh, rh, diff, dir; struct avlnode **b; static void (*rotator[2])(struct avlnode **) = { left_rotate, right_rotate }; lh = get_height((*node)->child[CLD_L]); rh = get_height((*node)->child[CLD_R]); diff = abs(lh - rh); if (diff > 1){ // check is LL|RR or LR|RL case // check is L or R // 0: L, 1: R dir = (lh > rh); // is L case b = &(*node)->child[!dir]; // L case -> L, R case -> R lh = get_height((*b)->child[CLD_L]); rh = get_height((*b)->child[CLD_R]); // BUGFIX: `(lh != rh)` to bypass L and R only case. if ((lh != rh) && ((lh > rh) != dir)){ // not the same case as parent // LR|RL case // L case = 1 -> LR -> left rotate // R case = 0 -> RL -> right rotate rotator[!dir](b); } rotator[dir](node); } else { // do nothing, just update. update_height(*node); } return; } static void left_rotate(struct avlnode **a){ struct avlnode *b = (*a)->child[CLD_R]; (*a)->child[CLD_R] = b->child[CLD_L]; b->child[CLD_L] = (*a); (*a) = b; /* A B / \ / \ a B -> A c / \ / \ b c a b */ update_height(b->child[CLD_L]); update_height(b); return; } static void right_rotate(struct avlnode **a){ struct avlnode *b = (*a)->child[CLD_L]; (*a)->child[CLD_L] = b->child[CLD_R]; b->child[CLD_R] = (*a); (*a) = b; /* A B / \ / \ B c -> a A / \ / \ a b b c */ // the content of (*a) is now b. update_height(b->child[CLD_R]); update_height(b); return; } static struct avlnode **node_min(struct avlnode **node){ struct avlnode **res = node; assert((*node) != NULL); for (;(*res)->child[CLD_L] != NULL;){ res = &(*res)->child[CLD_L]; } return res; } static void node_trav(struct avlnode *node, int depth){ if (node == NULL){ return; } trav(node->child[CLD_L], depth + 1); for (int i = 0; i < depth; ++i){ printf(" "); } printf("%d <%d>\n", node->key, node->height); trav(node->child[CLD_R], depth + 1); return; } static struct avlnode *node_alloc(int key, int val){ struct avlnode *node; node = calloc(1, sizeof(struct avlnode)); node->key = key; node->val = val; return node; } static void node_free(struct avlnode *node){ if (node == NULL){ return; } node_free(node->child[CLD_L]); node_free(node->child[CLD_R]); free(node); return; } static int node_insert(struct avlnode **node, int key, int val){ int ret = 0; struct avlnode *newnode = NULL; if (*node == NULL){ newnode = node_alloc(key, val); *node = newnode; } else { if ((*node)->key > key){ ret = node_insert(&(*node)->child[CLD_L], key, val); } else if ((*node)->key < key) { ret = node_insert(&(*node)->child[CLD_R], key, val); } else { // key is occupied. ret = -1; } } if (ret == -1){ // no insert is made, bail out. return ret; } node_fix(node); return 0; } static int node_delete(struct avlnode **node, int key){ int ret = 0; struct avlnode *tmp = NULL, **victim; if ((*node) == NULL){ // cannot find target, bail out. ret = -1; } else { if (key < (*node)->key){ ret = node_delete(&(*node)->child[CLD_L], key); } else if (key > (*node)->key){ ret = node_delete(&(*node)->child[CLD_R], key); } else { // find target // one child|no child case if ((*node)->child[CLD_L] == NULL){ tmp = (*node); *node = (*node)->child[CLD_R]; free(tmp); ret = 0; } else if ((*node)->child[CLD_R] == NULL){ tmp = (*node); *node = (*node)->child[CLD_L]; free(tmp); ret = 0; } else { // 2 child case victim = node_min(&(*node)->child[CLD_R]); // copy key & val (*node)->key = (*victim)->key; (*node)->val = (*victim)->val; key = (*victim)->key; ret = node_delete(&(*node)->child[CLD_R], key); } } } // bail out or do fixup if (ret == -1){ return ret; } if ((*node) != NULL){ node_fix(node); } return ret; } static void node_validate(struct avlnode *node){ int lh, rh, diff; if (node == NULL){ return; } else { node_validate(node->child[CLD_L]); node_validate(node->child[CLD_R]); } // check basic BST rules if (node->child[CLD_L] != NULL){ assert(node->child[CLD_L]->key < node->key); } if (node->child[CLD_R] != NULL){ assert(node->child[CLD_R]->key > node->key); } // check AVL tree rules lh = get_height(node->child[CLD_L]); rh = get_height(node->child[CLD_R]); diff = abs(lh - rh); if (diff >= 2){ node_trav(node, 0); printf("<diff = %d, lh = %d, rh = %d>\n", diff, lh, rh); printf("<left = %p>\n", node->child[CLD_L]); printf("<right = %p>\n", node->child[CLD_R]); assert(diff < 2); } return; } struct avltree *avl_alloc(void){ struct avltree *tree; tree = calloc(1, sizeof(struct avltree)); return tree; } void avl_purge(struct avltree *tree){ node_free(tree->root); tree->count = 0; return; } void avl_free(struct avltree *tree){ node_free(tree->root); free(tree); return; } int avl_get(struct avltree *tree, int key, int *res){ int ret = 0; struct avlnode *tmp; tmp = tree->root; for (;tmp != NULL;){ if (key > tmp->key){ tmp = tmp->child[CLD_R]; } else if (key < tmp->key){ tmp = tmp->child[CLD_L]; } else { *res = tmp->val; break; } } if (tmp == NULL){ ret = -1; } return ret; } int avl_insert(struct avltree *tree, int key, int val){ int ret; ret = node_insert(&tree->root, key, val); if (ret == 0){ tree->count++; } return ret; } int avl_delete(struct avltree *tree, int key){ int ret; ret = node_delete(&tree->root, key); if (ret == 0){ tree->count--; } return ret; } void avl_validate(struct avltree *tree){ return node_validate(tree->root); }
KIodine/naiveds
bstree/main.c
#include <stdio.h> #include <assert.h> #include <unistd.h> #include <fcntl.h> #include <stdint.h> #include "bstree.h" #define NL "\n" static void node_traversal(struct bstnode *node){ if (node == NULL){ return; } node_traversal(node->left); printf("%d"NL, node->key); node_traversal(node->right); } void basic_test(void){ struct bstree *tree; int res, ret_code; printf("alloc"NL); tree = bstree_alloc(); printf("set"NL); bstree_set(tree, 123, 456); bstree_set(tree, 124, 455); bstree_set(tree, 122, 454); printf("get"NL); bstree_get(tree, 123, &res); assert(res == 456); bstree_get(tree, 122, &res); assert(res == 454); ret_code = bstree_get(tree, 0, &res); assert(ret_code == BST_NOELEM); printf("delete"NL); ret_code = bstree_delete(tree, 122); assert(ret_code == BST_OK); ret_code = bstree_delete(tree, 122); assert(ret_code == BST_NOELEM); ret_code = bstree_delete(tree, 123); assert(ret_code == BST_OK); printf("free"NL); bstree_free(tree); return; } void torture_test(void){ /* insert 65536 ints and delete some of them, finally free */ unsigned int const count = 65536; uint32_t *buffer; buffer = malloc(sizeof(uint32_t)*count); int fd = open("./testints", O_RDONLY); read(fd, buffer, sizeof(uint32_t)*count); close(fd); struct bstree *tree = bstree_alloc(); printf("torture set"NL); for (int i = 0; i < count; ++i){ bstree_set(tree, buffer[i], 0); } printf("torture delete"NL); for (int i = 0; i < 8000; ++i){ bstree_delete(tree, buffer[1337+i]); } printf("torture free"NL); bstree_free(tree); free(buffer); return; } int main(void){ basic_test(); torture_test(); return 0; }
KIodine/naiveds
threaded-avltree/include/avltree.h
#ifndef AVLTREE_H #define AVLTREE_H #include <string.h> #include <stddef.h> #include "list.h" /* TODO: - Implement `threaded-avltree`. - Add a `struct list node` member. - Add implementation of insert in `avl_insert`. - Add implementation of remove in `avl_delete`. - Update `avl_replace`. - Add `avl_iter` macro for iteration. - Add `avl_min` and `avl_max` inline functions. */ // copy from <linux/kernel.h> and strip debug stuffs. #define container_of(ptr, type, member) ({ \ void *__mptr = (void *)(ptr); \ ((type *)(__mptr - offsetof(type, member))); }) struct avlnode; /* eval: a <cmp op> b ret val <--- -1| 0 | 1 ---> (int) meaning <--- LT|EQL|GT ---> ex: cmp(a, b) -> -1 equal to a < b */ typedef int (*avl_cmp_t)(struct avlnode const *a, struct avlnode const *b); struct avlnode { struct avlnode *child[2], *parent; struct list node; int factor; }; struct avltree { struct avlnode *root; struct list head; int count; avl_cmp_t cmp; }; enum { // type generic comp res NODE_LT = -1, NODE_EQ = 0, NODE_GT = 1, // access child pointer CLD_L = 0, CLD_R = 1, }; #define _STMT(stmt) \ do { \ (stmt) \ } while (0); #define avl_tree_decl(sym, comparator) \ struct avltree (sym) = { \ .root = NULL, \ .cmp = &(comparator), \ .count = 0, \ } static inline void avl_tree_init(struct avltree *tree, avl_cmp_t cmp){ tree->root = NULL; tree->cmp = cmp; tree->count = 0; tree->head.prev = &tree->head; tree->head.next = &tree->head; return; }; #define avl_node_init(node) \ _STMT( \ memset((node), 0, sizeof(struct avlnode));\ ) static inline struct avlnode *avl_get_min(struct avltree *tree){ return container_of(tree->head.next, struct avlnode, node); } static inline struct avlnode *avl_get_max(struct avltree *tree){ return container_of(tree->head.prev, struct avlnode, node); } struct avlnode *avl_insert(struct avltree *tree, struct avlnode *node); struct avlnode *avl_get(struct avltree *tree, struct avlnode *hint); struct avlnode *avl_delete(struct avltree *tree, struct avlnode *node); struct avlnode *avl_replace( struct avltree *tree, struct avlnode *node, struct avlnode *sub ); #endif /* AVLTREE_H */
KIodine/naiveds
intrusive-avltree/src/avldbg.c
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include "avldbg.h" #define NL "\n" static void node_print(struct avlnode *node, int depth); static void node_validate(struct avlnode *node, avl_cmp_t cmp); void avl_print(struct avltree *tree){ putchar('\n'); node_print(tree->root, 0); return; } static void node_print(struct avlnode *node, int depth){ if (node == NULL){ return; } node_print(node->child[CLD_R], depth + 1); for (int i = 0; i < depth; ++i){ printf(" "); } printf("+-[%d]"NL, node->factor); node_print(node->child[CLD_L], depth + 1); return; } void avl_validate(struct avltree *tree){ node_validate(tree->root, tree->cmp); return; } static void node_validate(struct avlnode *node, avl_cmp_t cmp){ int res; if (node == NULL){ return; } // AVL basic property assert(abs(node->factor) < 2); // BST basic property if (node->child[CLD_L] && node->child[CLD_R]){ res = cmp(node->child[CLD_L], node->child[CLD_R]); assert(res < 0); } // more strict basic attribute test if (!node->child[CLD_L] && !node->child[CLD_R]){ assert(node->factor == 0); } if (node->child[CLD_L] != NULL){ assert(node->child[CLD_L]->parent == node); } if (node->child[CLD_R] != NULL){ assert(node->child[CLD_R]->parent == node); } node_validate(node->child[CLD_L], cmp); node_validate(node->child[CLD_R], cmp); return; }
KIodine/naiveds
rbtree/main.c
<reponame>KIodine/naiveds #include <stdio.h> #include <assert.h> #include <unistd.h> #include <fcntl.h> #include <stdint.h> #include "rbtree.h" #define NL "\n" static void node_traversal(struct rbtnode *node){ if (node == NULL){ return; } node_traversal(node->left); printf("%d"NL, node->key); node_traversal(node->right); } void basic_test(void){ struct rbtree *tree; int res, ret_code; printf("alloc"NL); tree = rbtree_alloc(); printf("set"NL); rbtree_set(tree, 123, 456); rbtree_validate(tree); rbtree_set(tree, 124, 455); rbtree_set(tree, 122, 454); printf("get"NL); rbtree_get(tree, 123, &res); assert(res == 456); rbtree_get(tree, 122, &res); assert(res == 454); ret_code = rbtree_get(tree, 0, &res); assert(ret_code == RBT_NOELEM); printf("delete"NL); ret_code = rbtree_delete(tree, 122); assert(ret_code == RBT_OK); ret_code = rbtree_delete(tree, 122); assert(ret_code == RBT_NOELEM); ret_code = rbtree_delete(tree, 123); assert(ret_code == RBT_OK); rbtree_validate(tree); rbtree_purge(tree); rbtree_set(tree, 165, 36213); printf("free"NL); rbtree_free(tree); return; } void torture_test(void){ /* insert 65536 ints and delete some of them, finally free */ unsigned int const count = 65536; uint32_t *buffer; buffer = malloc(sizeof(uint32_t)*count); int fd = open("./testints", O_RDONLY); read(fd, buffer, sizeof(uint32_t)*count); close(fd); struct rbtree *tree = rbtree_alloc(); printf("torture set"NL); for (int i = 0; i < count; ++i){ rbtree_set(tree, buffer[i], 0); } rbtree_validate(tree); printf("torture delete"NL); for (int i = 0; i < 8000; ++i){ rbtree_delete(tree, buffer[1337+i]); } rbtree_validate(tree); printf("torture purge"NL); rbtree_purge(tree); printf("torture set2"NL); for (int i = 0; i < count; ++i){ rbtree_set(tree, buffer[i], 0); } rbtree_validate(tree); printf("torture free"NL); rbtree_free(tree); free(buffer); return; } int main(void){ basic_test(); torture_test(); return 0; }
KIodine/naiveds
rbtree/rbtree.h
#ifndef RBTREE_H #define RBTREE_H #include <stdlib.h> #include <assert.h> struct rbtree { unsigned int count; struct rbtnode *root, *nil; }; struct rbtnode { int color; int key, val; struct rbtnode *left, *right, *parent; }; enum { RBT_OK, RBT_NOELEM, }; enum { COLOR_RED, COLOR_BLACK, }; struct rbtree *rbtree_alloc(void); void rbtree_free(struct rbtree *tree); int rbtree_set(struct rbtree *tree, int key, int val); int rbtree_get(struct rbtree *tree, int key, int *res); int rbtree_delete(struct rbtree *tree, int key); void rbtree_purge(struct rbtree *tree); int rbtree_validate(struct rbtree *tree); #endif
KIodine/naiveds
bstree/bstree.h
#ifndef BSTREE_H #define BSTREE_H #include <stdlib.h> struct bstree { unsigned int count; struct bstnode *root; }; struct bstnode { int key, val; struct bstnode *left, *right; }; enum { BST_OK, BST_NOELEM, }; struct bstree *bstree_alloc(void); void bstree_free(struct bstree *tree); int bstree_set(struct bstree *tree, int key, int val); int bstree_get(struct bstree *tree, int key, int *res); int bstree_delete(struct bstree *tree, int key); void bstree_purge(struct bstree *tree); #endif
KIodine/naiveds
avltree/main.c
<filename>avltree/main.c<gh_stars>1-10 #include <stdio.h> #include <stdint.h> #include <assert.h> #include <unistd.h> #include <fcntl.h> #include "avltree.h" #define NL "\n" #define NINT32 4096 void trav(struct avlnode *node, int depth){ if (node == NULL){ return; } trav(node->child[CLD_L], depth + 1); for (int i = 0; i < depth; ++i){ printf(" "); } printf("%d <%d>"NL, node->key, node->height); trav(node->child[CLD_R], depth + 1); return; } void basic_test(void){ int res, tmp; struct avltree *tree; tree = avl_alloc(); printf("basic insert test..."NL); for (int i = 0; i < 64; ++i){ res = avl_insert(tree, i, 0); assert(res == 0); } avl_validate(tree); printf("yes"NL); printf("basic get test..."NL); for (int i = 0; i < 64; ++i){ res = avl_get(tree, i, &tmp); assert(res == 0); } avl_validate(tree); printf("yes"NL); printf("basic delete test..."NL); for (int i = 30; i < 62; ++i){ res = avl_delete(tree, i); assert(res == 0); } avl_validate(tree); printf("yes"NL); avl_free(tree); tree = NULL; return; } void torture_test(void){ int fd, res, qres; uint32_t *elems; struct avltree *tree; tree = avl_alloc(); elems = malloc(sizeof(uint32_t)*NINT32); fd = open("./test.bin", O_RDONLY); read(fd, elems, sizeof(uint32_t)*NINT32); close(fd); printf("torture insert"NL); for (int i = 0; i < NINT32; ++i){ res = avl_insert(tree, elems[i], 0); assert(res == 0); } avl_validate(tree); printf("done"NL); printf("torture get"NL); for (int i = 0; i < NINT32; ++i){ res = avl_get(tree, elems[i], &qres); assert(res == 0); } printf("done"NL); printf("torture delete"NL); for (int i = 0; i < 1000; ++i){ res = avl_delete(tree, elems[i]); } avl_validate(tree); printf("done"NL); avl_free(tree); tree = NULL; free(elems); return; } int main(void){ printf("start test"NL); basic_test(); torture_test(); return 0; }
KIodine/naiveds
doubly-linked-list/dllist.h
<reponame>KIodine/naiveds<filename>doubly-linked-list/dllist.h #ifndef DLLIST_H #define DLLIST_H #include <stdlib.h> struct dllnode { int val; struct dllnode *prev, *next; }; struct dllist { int count; struct dllnode first; }; enum { DLL_OK, DLL_NOELEM }; struct dllist *dll_alloc(void); void dll_free(struct dllist *list); void dll_purge(struct dllist *list); int dll_delete(struct dllist *list, int val); int dll_push(struct dllist *list, int val); int dll_pop(struct dllist *list, int *res); int dll_append(struct dllist *list, int val); int dll_get(struct dllist *list, int *res); #endif
KIodine/naiveds
avltree/avltree.h
<filename>avltree/avltree.h #ifndef AVLTREE_H #define AVLTREE_H #include <stdio.h> #include <stdlib.h> #include <assert.h> // TODO: use `struct avlnode *[2]` to store left and right children. // by doing so, specific style of coding can be performed. struct avlnode { struct avlnode *child[2]; int key, val, height; }; struct avltree { struct avlnode *root; int count; }; enum { CLD_L = 0, CLD_R = 1, }; struct avltree *avl_alloc(void); void avl_purge(struct avltree *tree); void avl_free(struct avltree *tree); int avl_insert(struct avltree *tree, int key, int val); int avl_get(struct avltree *tree, int key, int *res); int avl_delete(struct avltree *tree, int key); void avl_validate(struct avltree *tree); // void avl_avlize(struct avltree *tree); #endif /* AVLTREE_H */
KIodine/naiveds
binheap/main.c
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include "binheap.h" #define ARRSZ(array) ((sizeof(array))/sizeof(array[0])) #define RESET "\e[0m" #define REDTEXT "\e[31m" #define HEAPSZ 8192 int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; /* --- util routines --- */ static void verify_maxheap(int *arr, int len){ int cur = (len - 1) >> 1, parent; if (len == 0){ return; } for (; cur != 0;){ parent = ((cur + 1) >> 1) - 1; if (arr[cur] > arr[parent]){ printf( REDTEXT"[%d]=%d < [%d]=%d?\n"RESET, cur, arr[cur], parent, arr[parent] ); assert(arr[cur] < arr[parent]); } //assert(cur > parent); cur = cur - 1;//parent; } return; } /* --- test routines --- */ static void test_maxheapify(void){ int sz = ARRSZ(arr); maxheapify(arr, sz); for (int i = 0; i < sz; ++i){ printf("%d ", arr[i]); } putchar('\n'); verify_maxheap(arr, sz); return; } static void test_binheap(void){ struct binheap *heap; int sz = HEAPSZ, res; heap = binheap_alloc(sz); for (int i = 0; binheap_insert(heap, i) == 0; i++){ ; } assert(heap->count == sz); verify_maxheap(heap->arr, heap->count); for (;binheap_extract(heap, &res) == 0;){ //printf("%d ", res); verify_maxheap(heap->arr, heap->count); } putchar('\n'); binheap_free(heap); return; } int main(void){ printf("--- Test maxheapify ---\n"); test_maxheapify(); printf("--- test binheap ---\n"); test_binheap(); return 0; }
KIodine/naiveds
intrusive-rbtree/rbtree.h
#ifndef RBTREE_H #define RBTREE_H #include <stdlib.h> #include <stddef.h> #include <assert.h> /* or just include `linux/kernel.h`? */ #define container_of(ptr, type, member) ({ \ void *__mptr = (void*)(ptr); \ (type*)(__mptr - offsetof(type, member)); \ }) #define rbt_is_black(node) ((node)->color == COLOR_BLACK) #define rbt_is_red(node) ((node)->color == COLOR_RED) #define rbt_set_black(node) ((node)->color = COLOR_BLACK) #define rbt_set_red(node) ((node)->color = COLOR_RED) #define rbt_cpy_color(a, b) ((a)->color = (b)->color) struct rbtnode { int color; int key, val; struct rbtnode *left, *right, *parent; }; typedef int (*rbt_cmp_func)(struct rbtnode*, struct rbtnode*); struct rbtree { unsigned int count; rbt_cmp_func cmp; struct rbtnode *root, *nil; }; enum { RBT_OK, RBT_NOELEM, RBT_EXISTED, }; enum { COLOR_RED, COLOR_BLACK, }; enum { CMP_LT = -1, CMP_GT = 1, CMP_EQ = 0, }; void rbtree_init(struct rbtree *tree, struct rbtnode *nil, rbt_cmp_func cmp); int rbtree_set(struct rbtree *tree, struct rbtnode *node); struct rbtnode *rbtree_get(struct rbtree *tree, struct rbtnode *hint); void rbtree_delete(struct rbtree *tree, struct rbtnode *node); int rbtree_validate(struct rbtree *tree); static struct rbtnode *rbtree_min(struct rbtnode *node, struct rbtnode *nil){ for (;node->left != nil;){ node = node->left; } return node; }; #endif
KIodine/naiveds
singly-linked-list/sllist.h
<reponame>KIodine/naiveds #ifndef SLLIST_H #define SLLIST_H #include <stdlib.h> #include <stdint.h> struct sllnode { int val; struct sllnode *next; }; struct sllist { int count; struct sllnode *first; }; enum { SLL_OK, SLL_NOELEM, }; struct sllist *sll_alloc(void); void sll_free(struct sllist *list); void sll_purge(struct sllist *list); int sll_push(struct sllist *list, int val); int sll_append(struct sllist *list, int val); int sll_insert(struct sllist *list, unsigned int pos, int val); int sll_get(struct sllist *list, unsigned int pos, int *res); int sll_pop(struct sllist *list, int *res); int sll_delete(struct sllist *list, int val); void sll_reverse(struct sllist *list); #define LIST_TRAVERSE(list, sym) \ for (struct sllnode *sym = list->first; sym != NULL; sym = sym->next) #endif
KIodine/naiveds
rbtree/rbtree.c
#include "rbtree.h" #ifdef __GNUC__ #define FORCE_INLINE __attribute__((always_inline)) #elif #define FORCE_INLINE #endif enum chiral { CHIRAL_LEFT = 0, CHIRAL_RIGHT = 1 }; static inline FORCE_INLINE struct rbtnode *node_alloc(int key, int val){ struct rbtnode *node = NULL; node = calloc(1, sizeof(struct rbtnode)); node->key = key; node->val = val; return node; } static struct rbtnode *rbtnode_alloc(struct rbtree *tree, int key, int val){ struct rbtnode *node = NULL; node = node_alloc(key, val); /* * the color of node is naturally red because of the * order of enum order of COLOR_* constants. */ node->color = COLOR_RED; node->parent = tree->nil; node->left = tree->nil; node->right = tree->nil; return node; } static void tree_purge(struct rbtnode* start, struct rbtnode *nil){ if (start == nil){ return; } tree_purge(start->left, nil); tree_purge(start->right, nil); free(start); return; } static int node_validate(struct rbtree *tree, struct rbtnode *node){ int bh_l = 0, bh_r; if (node == tree->nil){ return 0; } if (node->color == COLOR_RED){ /* constrain #4 */ assert(node->parent->color == COLOR_BLACK); } bh_l = node_validate(tree, node->left); bh_r = node_validate(tree, node->right); /* constrain #5 */ assert(bh_l == bh_r); if (node->color == COLOR_BLACK){ bh_l += 1; } return bh_l; } /* TODO modify these functions */ static struct rbtnode **find_precedence( struct rbtnode **start, struct rbtnode *nil ){ /* find the rightmost node of left subtree */ struct rbtnode **can; /* the candidate */ can = &(*start)->left; if (*can == nil){ return NULL; /* just for sentinel */ } for (;(*can)->right != nil;){ can = &(*can)->right; } return can; } static struct rbtnode **find_successor( struct rbtnode **start, struct rbtnode *nil ){ /* find the leftmost node of right subtree */ struct rbtnode **can; can = &(*start)->right; if (*can == nil){ return NULL; } /* only modify parent if candidate exists */ for (;(*can)->left != nil;){ can = &(*can)->left; } return can; } static void left_rotate(struct rbtree *tree, struct rbtnode *x){ struct rbtnode *y = x->right, *nil = tree->nil; // struct rbtnode **y = &(*x)->right; x->right = y->left; if (y->left != nil){ y->left->parent = x; } y->parent = x->parent; // struct rbtnode **x; // *x = *y; /* * just modify the field holds x, in other words, x is one of: * 1) the address of root of tree * 2) the address of left or right child of parent */ if (x->parent == nil){ tree->root = y; } else if (x == x->parent->left){ x->parent->left = y; } else { // x == x->parent->right x->parent->right = y; } y->left = x; x->parent = y; return; } static void right_rotate(struct rbtree *tree, struct rbtnode *x){ struct rbtnode *y = x->left, *nil = tree->nil; x->left = y->right; if (y->right != nil){ y->right->parent = x; } y->parent = x->parent; if (x->parent == nil){ tree->root = y; } else if (x == x->parent->left){ x->parent->left = y; } else { x->parent->right = y; } y->right = x; x->parent = y; return; } /* TODO: tighten the code flow */ static void insert_fix(struct rbtree *tree, struct rbtnode *node){ struct rbtnode *uncle, *parent, *gparent; void (*rotator[2])(struct rbtree*, struct rbtnode*) = { left_rotate, right_rotate }; /* array of function pointers*/ int chiral = 0, do_case2 = 0; for (;node->parent->color == COLOR_RED;){ parent = node->parent; gparent = parent->parent; if (parent == gparent->left){ uncle = gparent->right; chiral = CHIRAL_LEFT; /* left */ do_case2 = (node == parent->right); } else { uncle = gparent->left; chiral = CHIRAL_RIGHT; /* right */ do_case2 = (node == parent->left); } if (uncle->color == COLOR_RED){ /* case #1 */ parent->color = COLOR_BLACK; uncle->color = COLOR_BLACK; gparent->color = COLOR_RED; node = gparent; continue; } if (do_case2){ /* case #2 */ node = node->parent; rotator[chiral](tree, node); parent = node->parent; gparent = parent->parent; } /* case #3 */ parent->color = COLOR_BLACK; gparent->color = COLOR_RED; rotator[!chiral](tree, gparent); } tree->root->color = COLOR_BLACK; return; } static void delete_fix(struct rbtree *tree, struct rbtnode *node){ struct rbtnode *sibling, *parent; void (*rotator[2])(struct rbtree*, struct rbtnode*) = { left_rotate, right_rotate }; /* array of function pointers*/ /* * By abusing the fact boolean in C is actually evaluate to * **0** and **1**, we can turn logic operation results into switch of * rotation functions. * Further, use **!<boolean>** to switch between 0 and 1. */ /* TODO: cache nephews and access them use chiral */ int chiral; struct rbtnode *nephews[2]; for (;node != tree->root && node->color == COLOR_BLACK;){ parent = node->parent; if (node == parent->left){ sibling = parent->right; chiral = CHIRAL_LEFT; } else { sibling = parent->left; chiral = CHIRAL_RIGHT; } nephews[CHIRAL_LEFT] = sibling->left; nephews[CHIRAL_RIGHT] = sibling->right; if (sibling->color == COLOR_RED){ /* case #1 */ sibling->color = COLOR_BLACK; parent->color = COLOR_RED; rotator[chiral](tree, parent); if (chiral == CHIRAL_LEFT){ sibling = parent->right; } else { sibling = parent->left; } nephews[CHIRAL_LEFT] = sibling->left; nephews[CHIRAL_RIGHT] = sibling->right; } if (nephews[CHIRAL_LEFT]->color == COLOR_BLACK && nephews[CHIRAL_RIGHT]->color == COLOR_BLACK){ /* case #2 */ sibling->color = COLOR_RED; node = parent; continue; } if (nephews[chiral]->color == COLOR_RED){ /* case #3 */ nephews[chiral]->color = COLOR_BLACK; sibling->color = COLOR_RED; rotator[!chiral](tree, sibling); if (chiral == CHIRAL_LEFT){ sibling = parent->right; } else { sibling = parent->left; } nephews[CHIRAL_LEFT] = sibling->left; nephews[CHIRAL_RIGHT] = sibling->right; } /* case #4 */ sibling->color = parent->color; parent->color = COLOR_BLACK; nephews[!chiral]->color = COLOR_BLACK; rotator[chiral](tree, parent); node = tree->root; } node->color = COLOR_BLACK; return; } struct rbtree *rbtree_alloc(void){ struct rbtree *tree = NULL; struct rbtnode *nil = NULL; tree = calloc(1, sizeof(struct rbtree)); nil = node_alloc(0, 0); nil->color = COLOR_BLACK; nil->parent = nil; nil->left = nil; nil->right = nil; tree->nil = nil; tree->root = nil; return tree; } void rbtree_purge(struct rbtree *tree){ tree_purge(tree->root, tree->nil); tree->root = tree->nil; tree->count = 0; return; } void rbtree_free(struct rbtree *tree){ tree_purge(tree->root, tree->nil); free(tree->nil); free(tree); return; } int rbtree_validate(struct rbtree *tree){ /* constrain #2 */ assert(tree->root->color == COLOR_BLACK); /* constrain #3 */ assert(tree->nil->color == COLOR_BLACK); /* constrain #4 #5 */ node_validate(tree, tree->root); return 0; } int rbtree_set(struct rbtree *tree, int key, int val){ struct rbtnode *new, *parent, *nil = tree->nil, **indirect; indirect = &tree->root; parent = *indirect; for (;;){ // this field is containing "NIL" if ((*indirect) == nil){ /* we've found an empty place, implies no corresponding key was found. */ new = rbtnode_alloc(tree, key, val); new->parent = parent; // TODO: find a way to link parent *indirect = new; tree->count++; insert_fix(tree, new); break; } /* assured (*indirect) is not NULL */ /* preserve which way coming and proceed */ parent = *indirect; if (key < (*indirect)->key){ /* indirect points to the field instead */ indirect = &(*indirect)->left; } else if (key > (*indirect)->key){ indirect = &(*indirect)->right; } else { /* we're pointing is what we're looking for */ (*indirect)->val = val; break; } } return RBT_OK; } int rbtree_get(struct rbtree *tree, int key, int *res){ struct rbtnode *cur, *nil = tree->nil; cur = tree->root; for (;cur != nil;){ if (cur->key == key){ *res = cur->val; break; } if (key < cur->key){ cur = cur->left; } else { cur = cur->right; } } if (cur == nil){ return RBT_NOELEM; } return RBT_OK; } int rbtree_delete(struct rbtree *tree, int key){ struct rbtnode **indirect = &tree->root, **victim, *orphan, *hold, *nil = tree->nil; for (;*indirect != nil;){ if ((*indirect)->key == key){ /* do delete stuff */ victim = find_precedence(indirect, nil); // we can abuse pointer to make even shorter/cleaner code here. if (victim != NULL){ // abuse ver: *victim = (*victim)->left; orphan = (*victim)->left; break; } victim = find_successor(indirect, nil); if (victim != NULL){ orphan = (*victim)->right; break; } /* it is a leaf node */ orphan = nil; victim = indirect; /* bypassing: * 1) after loop condition check * 2) value copy */ goto finish; } if (key < (*indirect)->key){ indirect = &(*indirect)->left; } else { indirect = &(*indirect)->right; } /* then continue */ } if (*indirect == nil){ /* can't find the entry */ return RBT_NOELEM; } /* we've completed the adopt, time to kill the victim */ (*indirect)->key = (*victim)->key; (*indirect)->val = (*victim)->val; finish: /* * set parent anyway (even it's `nil`), we'll use orphan as the * start of delete_fix. */ hold = *victim; orphan->parent = (*victim)->parent; // "unlink" the node. *victim = orphan; /* if node we're deleting is black, we have to fix it */ if (hold->color == COLOR_BLACK){ delete_fix(tree, orphan); } free(hold); tree->count--; return RBT_OK; }
KIodine/naiveds
threaded-avltree/test/main.c
<reponame>KIodine/naiveds #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <assert.h> #include <fcntl.h> #include <time.h> #include "avltree.h" #include "avldbg.h" #define NL "\n" #define NNUMS 4096 struct pair { struct avlnode node; int key; }; struct timespec ts_start, ts_dt; double dt_ms_f64 = 0.0; static int pair_cmp(struct avlnode const *a, struct avlnode const *b){ struct pair *pa, *pb; int cmpres; pa = container_of(a, struct pair, node); pb = container_of(b, struct pair, node); if (pa->key > pb->key){ cmpres = NODE_GT; } else if (pa->key < pb->key){ cmpres = NODE_LT; } else { cmpres = NODE_EQ; } return cmpres; } static void shuffle(int32_t *arr, size_t n){ unsigned int i_excg, tmp; srand(9997); /* for test purpose, this produces same result every time. */ for (size_t i = 0; i < n; ++i){ i_excg = rand(); i_excg %= n; tmp = arr[i]; arr[i] = arr[i_excg]; arr[i_excg] = tmp; } return; } static void do_test(void){ //avl_tree_decl(tree, pair_cmp); struct avltree tree; int const N_NODES = 100000; int *narr; struct pair *parr, *tmp_pair, hint_pair; struct avlnode *tmp_node; avl_tree_init(&tree, pair_cmp); memset(&hint_pair.node, 0, sizeof(struct avlnode)); parr = calloc(N_NODES, sizeof(struct pair)); narr = malloc(N_NODES*sizeof(int)); for (int i = 0; i < N_NODES; ++i){ narr[i] = i; } shuffle(narr, N_NODES); printf("operating on %d nodes."NL, N_NODES); printf("test insert..."); clock_gettime(CLOCK_MONOTONIC, &ts_start); for (int i = 0; i < N_NODES; ++i){ parr[i].key = narr[i]; tmp_node = avl_insert(&tree, &parr[i].node); assert(tmp_node == &parr[i].node); } clock_gettime(CLOCK_MONOTONIC, &ts_dt); ts_dt.tv_sec -= ts_start.tv_sec; ts_dt.tv_nsec -= ts_start.tv_nsec; dt_ms_f64 = ((double)ts_dt.tv_sec)*1e6 + ((double)ts_dt.tv_nsec)/1e3; dt_ms_f64 /= (double)N_NODES; avl_validate(&tree); printf("ok: %.3f us/op"NL, dt_ms_f64); /* ----- */ printf("test get..."); clock_gettime(CLOCK_MONOTONIC, &ts_start); for (int i = 0; i < N_NODES; ++i){ hint_pair.key = narr[i]; tmp_node = avl_get(&tree, &hint_pair.node); assert(tmp_node != NULL); tmp_pair = container_of(tmp_node, struct pair, node); assert(tmp_pair->key == narr[i]); } clock_gettime(CLOCK_MONOTONIC, &ts_dt); ts_dt.tv_sec -= ts_start.tv_sec; ts_dt.tv_nsec -= ts_start.tv_nsec; dt_ms_f64 = ((double)ts_dt.tv_sec)*1e6 + ((double)ts_dt.tv_nsec)/1e3; dt_ms_f64 /= (double)N_NODES; printf("ok: %.3f us/op"NL, dt_ms_f64); /* ----- */ printf("test delete..."); clock_gettime(CLOCK_MONOTONIC, &ts_start); for (int i = 500; i < 6000; ++i){ tmp_pair = &parr[i]; tmp_node = avl_delete(&tree, &tmp_pair->node); assert(tmp_node == &tmp_pair->node); } clock_gettime(CLOCK_MONOTONIC, &ts_dt); ts_dt.tv_sec -= ts_start.tv_sec; ts_dt.tv_nsec -= ts_start.tv_nsec; dt_ms_f64 = ((double)ts_dt.tv_sec)*1e6 + ((double)ts_dt.tv_nsec)/1e3; dt_ms_f64 /= (double)(6000-500); avl_validate(&tree); printf("ok: %.3f us/op"NL, dt_ms_f64); /* ----- */ printf("Function test done"NL); free(parr); free(narr); return; } int main(void){ // forces stdout flush setbuf(stdout, NULL); do_test(); return 0; }
KIodine/naiveds
arrayq/main.c
#include <stdio.h> #include <assert.h> #include "fifoq.h" #define NL "\n" #define ARRSIZE(arr) sizeof(arr)/sizeof(arr[0]) int test_data[] = { 1, 2, 3, 4, 5 }; void test_fifoq(void){ int ret; struct fifoq *q; q = fifoq_alloc(17); assert(fifoq_is_empty(q)); printf("--- test push ---"NL); for (int i = 0; !fifoq_push(q, i); ++i){ ; } assert(fifoq_is_full(q)); printf("--- test get ---"NL); for (int i = 0; !fifoq_get(q, &ret); ++i){ ; } assert(fifoq_is_empty(q)); printf("--- test put ---"NL); for (int i = 0; !fifoq_put(q, i); ++i){ ; } assert(fifoq_is_full(q)); printf("--- test pop ---"NL); for (int i = 0; !fifoq_pop(q, &ret); ++i){ ; } assert(fifoq_is_empty(q)); fifoq_free(q); return; } int main(void){ test_fifoq(); return EXIT_SUCCESS; }