libreis 0.1.0
A simple header-based drop-in library
Loading...
Searching...
No Matches
reis.h
Go to the documentation of this file.
1
7#ifndef __REISLIB_COMMMON_H__
8#define __REISLIB_COMMMON_H__
9
10#include <stdlib.h>
11#include <unistd.h>
12#include <stdint.h>
13#include <string.h>
14#include <stdio.h>
15#include <dirent.h>
16#include <sys/stat.h>
17#include <sys/time.h>
18#include <sys/resource.h>
19#include <sys/types.h>
20#include <sys/prctl.h>
21#include <signal.h>
22#include <syslog.h>
23#include <time.h>
24#include <fcntl.h>
25#include <stdatomic.h>
26
27#if defined(__APPLE__)
28 #include <wchar.h>
29#elif defined(__linux__)
30 #include <wchar.h>
31 #include <wctype.h>
32 #include <ctype.h>
33#endif
34
35#define VERISION "0.1.0"
36
37#if defined(BENCHMARK) || defined(DEBUG)
38 #pragma message "You are currently using a debug version of reis library."
39#endif
40
41/* GENERAL SETTINGS */
42#define REISLIB_INT_MAX 2147483647
43#define CHARSET "abcdefghijklmnopqrstuvwxyz"
44#define CHARSET_LEN 26
45#define MAX_CHARSET_SIZE 256
46#define SUB 0x1A // an empty char as not to interfere with '\0'
47
48
49/* DATA STRUCTURES */
50#define MAX_DATASTRUCT_STRSIZ 100
51#define MAP_MAX 100
52
53#define MULTIMAP_DEFAULT_SIZE 16
54#define MULTIMAP_RESIZE_FACTOR 2
55
56#define REISLIB_HASHTABLE_INITIAL_CAPACITY 16
57#define REISLIB_HASH_FNV_OFFSET 14695981039346656037UL
58#define REISLIB_HASH_FNV_PRIME 1099511628211UL
59
60/* UNIX */
61#define BD_NO_CHDIR 01 // dont chdir("/")
62#define BD_NO_CLOSE_FILES 02 // dont close all open files
63#define BD_NO_REOPEN_STD_FDS 04 // dont reopen stdin/out/err
64
65#define BD_NO_UMASK0 010 // dont do umask(0)
66#define BD_MAX_CLOSE 8192 // max fds
67
68/* IO */
69#define ANSI_RED "\x1b[31m" // ANSI code used for color printing to stdout
70#define ANSI_GREEN "\x1b[32m"
71#define ANSI_YELLOW "\x1b[33m"
72#define ANSI_BLUE "\x1b[34m"
73#define ANSI_MAGENTA "\x1b[35m"
74#define ANSI_CYAN "\x1b[36m"
75#define ASNI_WHITE "\x1b[37m"
76
77#define ANSI_RESET "\x1b[0m" // ANSI reset needed to be called after color change
78
79#if defined(__GNUC__) || defined(__clang__)
80#define CHECK_PRINTF_FMT(a, b) __attribute__ ((format (printf, a, b)))
81#else
82#define CHECK_PRINTF_FMT(...)
83#endif
84//#define cprintfb(fg, bg, format, ...) fprintf(stdout, fg bg format ANSI_RESET, \
85// "\x1b[%dm\x1b[%dm%s%s", 30+fg, 40+bg,text,ANSI_RESET)
86
87
88typedef uint8_t u8;
89typedef uint16_t u16;
90typedef uint32_t u32;
91typedef uint64_t u64;
92typedef int8_t s8;
93typedef int16_t s16;
94typedef int32_t s32;
95typedef int64_t s64;
96typedef float f32;
97typedef double f64;
98typedef long double f128;
99
100#ifdef __cplusplus
101extern "C" {
102#endif
103// Ensure no conflicts if bool is already defined
104#if !defined(__cplusplus)
105 #if !defined(bool)
106 typedef enum __attribute__((__packed__)) {false, true} bool;
107 #endif
108#endif
109
110#define fnname(name) #name
111
112
113/* PAIR */
114#if !defined(Pair)
115typedef struct {
116 wchar_t *first;
117 wchar_t *second;
118} Pair;
119
120Pair * reisPairCreate( wchar_t *first, wchar_t *second );
121void reisPairFree( Pair *p );
122#endif
123
124/* VECTOR */
125#if !defined(Pair)
126typedef struct Vec2 Vec2;
127struct Vec2 {
128 int x;
129 int y;
130};
131
132Vec2* reisNewVec2( int x, int y );
133void reisDelVec2( Vec2* v );
134#endif
135
136/* MAP */
137#if !defined(Map)
138typedef struct Map Map;
139struct Map {
140 size_t size;
141 char keys[MAP_MAX][MAX_DATASTRUCT_STRSIZ];
142 int values[MAP_MAX];
143};
144
145Map * reisMapNew();
146void reisMapInsert(Map *m, char key[], int value);
147int reisMapGet(Map *m, char key[]);
148void reisMapPrint(Map *m);
149// TODO: Not finished
150void reisMapDel(Map *m);
151#endif
152
153/* DYNAMIC ARRAY / LIST */
154typedef struct {
155 void **data;
156 size_t len;
157 // Consider adding a pointer or something for the type of list?
158 char *type;
159} List;
160
161List* reisListNew( size_t n );
162void reisListDel( List *a );
163
164
165typedef struct wcs_dynarr_t wcs_dynarr_t;
167 wchar_t **items;
168 size_t size;
169 size_t allocated_size;
170};
171
172/* MULTIMAP
173=========== */
175 void *value;
176 struct MultiMapNode *next;
177};
178typedef struct MultiMapNode MultiMapNode;
179
180typedef struct {
181 wchar_t **keys;
182 MultiMapNode **values;
183 size_t size;
184 size_t capacity;
185} MultiMap;
186
187MultiMap * reisNewMultiMap();
188void reisMultiMapInsert(MultiMap *m, wchar_t *key, void *value, size_t size);
189void** reisMultiMapGet(MultiMap *m, wchar_t *key, size_t *numValues);
190void reisMultiMapPrint(MultiMap *m);
191void reisDelMultiMap(MultiMap *m);
192
193wcs_dynarr_t * wcs_dynarr_init();
194void wcs_dynarr_kill(wcs_dynarr_t *arr);
195void wcs_dynarr_push(wcs_dynarr_t *arr, wchar_t *item);
196
197
198/* TRIE
199 ======= */
200
201// Default to English but designed to be changed.
202static int xtTrieNumOfLetters = 26;
203
204typedef struct TrieNode TrieNode;
205struct TrieNode {
206 wchar_t data;
207 bool is_leaf;
208 TrieNode* children[];
209};
210
211TrieNode * TrieNodeInit(wchar_t data, int numOfLetters);
212void TrieNodeFree(TrieNode *node);
213
214TrieNode * TrieInsert(TrieNode *root, wchar_t *word);
215TrieNode * TrieDelete(TrieNode *root, wchar_t *word);
216
217bool TrieSearch(TrieNode *root, wchar_t *word);
218
219void TriePrint(TrieNode *root);
220bool TriePrintSearch(TrieNode *root, wchar_t *word);
221
222/* HASHTABLE (i.e. hashmap)
223 ========================== */
224// TODO Introduce this schema elsewhere.
225typedef struct {
226 enum string_type {
227 E_STRING,
228 E_WCSTRING
229 } type;
230
232 const char *str;
233 const wchar_t *wcs;
234 } value;
235
236 u32 length;
237} string_t;
238
239
240typedef struct {
241 string_t *key;
242 void *value;
244
245typedef struct {
246 hashtable_entry_t *entries;
247 size_t capacity;
248 size_t length;
250
251
252// long names
253hashtable_t * reisNewHashTable();
254void reisDelHashTable(hashtable_t *table);
255
256// return NULL if key not found
257void * HashTableGet_str(hashtable_t *table, const char *key);
258void * HashTableGet_wcs(hashtable_t *table, const wchar_t *key);
259#define reisHashTableGet(table,key) _Generic((key), \
260 char *: HashTableGet_str, \
261 const char *: HashTableGet_str, \
262 wchar_t *: HashTableGet_wcs \
263)(table, key)
264
265// If not already present in table, key is copied to newly allocated memory
266// Return NULL if out of memory
267const char * HashTableSet_str(hashtable_t *table, const char *key, void *value);
268const wchar_t * HashTableSet_wcs(hashtable_t *table, const wchar_t *key, void *value);
269#define reisHashTableSet(table,key,value) _Generic((key), \
270 char *: HashTableSet_str, \
271 const char *: HashTableSet_str, \
272 wchar_t *: HashTableSet_wcs \
273)(table, key, value)
274
275size_t reisHashTableLength(hashtable_t *table);
276
277/*TODO Add the iterators.*/
278typedef struct {
279 const char *key;
280 void *value;
281
282 hashtable_t *table;
283 size_t it;
285
286hashtable_iterator_t reisNewHashTableIterator(hashtable_t *table);
287
288bool reisHashTableIteratorNext(hashtable_iterator_t it);
289
290//short names
291#ifdef REISHASH_ABBR
292#define HT_New() reisNewHashTable()
293#define HT_Del(...) reisDelHashTable(__VA_ARGS__)
294#define HT_Get(...) reisHashTableGet(__VA_ARGS__)
295#define HT_Set(...) reisHashTableSet(__VA_ARGS__)
296#define HT_Length(...) reisHashTableLength(__VA_ARGS__)
297#endif
298
299
300/* UNIX CALLS */
301
302// 0 on success; -1 on error
303int reisDaemonize(const char *name, char* path, int flags);
304
305/* RANDOM NUMBER GENERATION */
306
312static inline size_t rng(size_t lb, size_t ub) {
313#if defined(__linux__) || defined(__APPLE__)
314 struct timespec spec;
315 timespec_get(&spec, TIME_UTC);
316 long long ns;
317 ns = spec.tv_nsec; //fractional
318 int seed = lb + ((22695477 * ns) % 4294967296) % (ub - lb + 1);
319 return seed;
320#else
321 return lb + ub * -1;
322#endif
323}
324
325static inline size_t unix_rng(size_t lb, size_t ub) {
326 int fd = open("/dev/urandom", O_RDONLY);
327 if(fd < 0) {
328 perror("open");
329 return -1;
330 }
331
332 unsigned int random;
333 ssize_t result = read(fd, &random, sizeof(random));
334 close(fd);
335
336 if(result != sizeof(random)) {
337 perror("read");
338 return -1;
339 }
340 return lb + (random % (ub - lb + 1));
341}
342
346inline int randi() {
347 return (int)rng(0, REISLIB_INT_MAX-1);
348}
349
350inline int randib(int lb, int ub) {
351 return (int)rng(lb, ub);
352}
353
354// generate random char
355inline char randc() {
356 return CHARSET[rng(0, CHARSET_LEN - 1)];
357}
358
359// generate random string of desired length, MUST FREE STR!
360inline char* rands(size_t len) {
361 char *str = (char*)malloc(len + 1);
362
363 size_t i;
364 for(i=0;i<len;i++) {
365 str[i] = randc();
366 }
367 str[len+1] = '\0';
368
369 return str;
370}
371
372
373/* MATH */
374int isNum(const char *str);
375
376/* IO */
377typedef struct {
378 char* path;
379 char* filename;
380 char* extension;
381 char* stem;
383
384filesystem_t* FS_Create( char* path );
385void FS_Destroy(filesystem_t* fs);
386
387/* FILE HANDLING
388=================*/
389char fpeek( FILE *stream );
390wchar_t fpeek_wc( FILE *stream );
391char fspeek( FILE *stream, long int offset, int position );
392int frpeek( FILE *stream, char c );
393int frdpeek( FILE *stream, char d );
394int fcounts( FILE *stream );
395void fcopy( FILE *dest, FILE *src );
396bool fexists( const char *file );
397bool fmove( char *oldpath, char *newpath );
398const char* ExtractFileName( const char *path );
399const char* ExtractFileExtension( const char *filename );
400bool dexists( const char *path );
401
402/* STDIN
403========*/
404void sgets(char* str, int n);
405bool PromptYesOrNo(const char *question);
406
407
408/* STDOUT
409==========*/
410CHECK_PRINTF_FMT(1, 2) void eprintf(const char *fmt, ...);
411CHECK_PRINTF_FMT(1, 3) void cprintf(const char * color, const char * fmt, ...);
412
413
414/* STRING MANIPULATION */
415char * strdupl(const char *str);
416char * strcov(char *str, const char *charset);
417wchar_t * wcscov(wchar_t *str, const wchar_t *charset);
418const char * strset(const char *string, const char *charset);
419const wchar_t * wcsset(const wchar_t *string, const wchar_t *charset);
420char * strpcat(char *dest, const char *src, size_t pos);
421wchar_t * wcspcat(wchar_t *dest, const wchar_t *src, size_t pos);
422char * chrcat(char *dest, const char src);
423wchar_t * wccat(wchar_t *dest, const wchar_t src);
424int strchrn(const char *string, char ch);
425int wcswcn(const wchar_t *string, wchar_t ch);
426wchar_t * wcsrev(wchar_t *str);
427char * strpre(char *str, char chr);
428wchar_t * wcspre(wchar_t *str, wchar_t chr);
429char * strpres(char *str, char* pre);
430wchar_t * wcspres(wchar_t *str, wchar_t *pre);
431char *strisdigit(char *str);
432wchar_t *wcsisdigit(wchar_t *str);
433long hash(const char* str);
434
435
436/* MEMORY
437 ======= */
438#ifndef MALLOC
439#define MALLOC(size) reisMalloc(size)
440#endif
441
442#ifndef CALLOC
443#define CALLOC(nitems,size) reisCalloc(nitems, size)
444#endif
445
446#ifndef REALLOC
447#define REALLOC(ptr,size) reisRealloc(ptr, size)
448#endif
449
450#ifndef MGET
451#define MGET(ptr) reisMemGet(ptr)
452#endif
453
454#ifndef FREE
455#define FREE(ptr) reisFree(ptr)
456#endif
457
458void * reisMalloc(size_t size);
459void * reisCalloc(size_t nitems, size_t size);
460void * reisRealloc(void *ptr, size_t size);
461size_t reisMemGet(void *ptr);
462size_t reisFree(void *ptr);
463size_t reisMemGetAll();
464
465/* SORTS */
466void reisInsertionSort( int arr[], int len );
467void reisMergeSort( int arr[], int len );
468void reisSort( int arr[], int len );
469
470
471/*
472 * A macro that tells the file using the library to opt into using
473 * condensed naming scheme.
474 */
475#ifdef REIS_SHORT_NAMES
476#define sort(...) reisSort(__VA_ARGS__)
477#endif
478
479
480#define foreach for
481
482#ifdef __cplusplus
483}
484#endif
485
486#endif
void * reisMalloc(size_t size)
Definition memory.c:8
const char char * strdupl(const char *str)
Implmentation of 'strdup,' using my MALLOC.
Definition string.c:16
int wcswcn(const wchar_t *string, wchar_t ch)
(Wide-char variant) Get number of times that ch appears in string.
Definition string.c:308
int fcounts(FILE *stream)
Character count of current line of buffer.
Definition io.c:106
Vec2 * reisNewVec2(int x, int y)
Create a new Vec2 datatype instance.
Definition data.c:20
bool fexists(const char *file)
Checks if file exists.
Definition io.c:239
int frpeek(FILE *stream, char c)
A recursive peek that goes to end of line or EOF to get # of occurences.
Definition io.c:61
char fspeek(FILE *stream, long int offset, int position)
View a character at position without moving pointer; Peeks a seek.
Definition io.c:42
char * strcov(char *str, const char *charset)
Checks if string covers all of charset.
Definition string.c:29
char * strisdigit(char *str)
Confirms that string is entirely composed on numbers.
Definition string.c:337
const char * ExtractFileExtension(const char *filename)
Returns file extension.
Definition io.c:140
char * strpcat(char *dest, const char *src, size_t pos)
concatenate but at a give 'p' position.
Definition string.c:131
int strchrn(const char *string, char ch)
Get number of times that ch appears in string.
Definition string.c:292
bool fmove(char *oldpath, char *newpath)
Move data from oldpath file to newpath.
Definition io.c:197
int frdpeek(FILE *stream, char d)
A recursive peek that goes till the delimter d.
Definition io.c:82
int randi()
Uses the defined INT_MAX instead of passing bounds.
Definition reis.h:346
wchar_t * wcsisdigit(wchar_t *str)
Confirms that wcstring is entirely composed on numbers.
Definition string.c:323
void fcopy(FILE *dest, FILE *src)
Copies data from src file to dest file.
Definition io.c:124
TrieNode * TrieInsert(TrieNode *root, wchar_t *word)
Inserts word onto the trie.
Definition trie.c:40
char fpeek(FILE *stream)
View the next character in stream, doesn't move pointer.
Definition io.c:21
filesystem_t * FS_Create(char *path)
Create a filesystem_t object.
Definition io.c:354
char * chrcat(char *dest, const char src)
Concatenate a char on to the end of a string.
Definition string.c:163
void FS_Destroy(filesystem_t *fs)
Terminates a filesystem_t object.
Definition io.c:377
const char * strset(const char *string, const char *charset)
Checks to see if string contains only characters in charset.
Definition string.c:85
wchar_t * wcsrev(wchar_t *str)
Reverses the wide character string.
Definition string.c:193
bool TrieSearch(TrieNode *root, wchar_t *word)
Searches for a given word.
Definition trie.c:82
bool PromptYesOrNo(const char *question)
Prompts the user with a yes or no question.
Definition io.c:291
wchar_t fpeek_wc(FILE *stream)
Same as fpeek but for wchar_t.
Definition io.c:32
const char * ExtractFileName(const char *path)
Returns filename.
Definition io.c:167
void * reisCalloc(size_t nitems, size_t size)
Definition memory.c:25
void sgets(char *str, int n)
A safe way to read input that ensures no misc LF or breaks in read string.
Definition io.c:274
wchar_t * wcspre(wchar_t *str, wchar_t chr)
Prepends a character to a wide character string.
Definition string.c:216
bool dexists(const char *path)
Checks if directory exists.
Definition io.c:251
void reisDelVec2(Vec2 *v)
Destroy a Vec2 instance.
Definition data.c:31
TrieNode * TrieDelete(TrieNode *root, wchar_t *word)
Deletes words from trie. Will try to delete the word sequence from trie only if it ends up in a leaf ...
Definition trie.c:64
Definition reis.h:154
Definition reis.h:139
Definition reis.h:174
Definition reis.h:180
Definition reis.h:115
Definition reis.h:205
Definition reis.h:127
Definition reis.h:377
Definition reis.h:240
Definition reis.h:278
Definition reis.h:245
Definition reis.h:225
Definition reis.h:166
Definition reis.h:231