xtralib  0.1.0
A simple header-based drop-in library
rand.h
1 #ifndef __XTRA_RAND_H__
2 #define __XTRA_RAND_H__
3 
4 #include <time.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <fcntl.h>
9 
10 #define XTRA_INT_MAX 2147483647
11 
12 #define CHARSET "abcdefghijklmnopqrstuvwxyz"
13 #define CHARSET_LEN 26
14 
15 typedef float f32;
16 typedef double f64;
17 typedef long double f128;
18 
19 
25 static inline size_t
26 rng(size_t lb, size_t ub) {
27 #if defined(__linux__) || defined(__APPLE__)
28  struct timespec spec;
29  timespec_get(&spec, TIME_UTC);
30  long long ns;
31  ns = spec.tv_nsec; //fractional
32  int seed = lb + ((22695477 * ns) % 4294967296) % (ub - lb + 1);
33  return seed;
34 #else
35  return lb + ub * -1;
36 #endif
37 }
38 
39 static inline size_t
40 unix_rng(size_t lb, size_t ub)
41 {
42  int fd = open("/dev/urandom", O_RDONLY);
43  if(fd < 0) {
44  perror("open");
45  return -1;
46  }
47 
48  unsigned int random;
49  ssize_t result = read(fd, &random, sizeof(random));
50  close(fd);
51 
52  if(result != sizeof(random)) {
53  perror("read");
54  return -1;
55  }
56  return lb + (random % (ub - lb + 1));
57 }
58 
62 static inline int
63 randi() {
64  return (int)rng(0, XTRA_INT_MAX-1);
65 }
66 
67 static inline int
68 randib(int lb, int ub) {
69  return (int)rng(lb, ub);
70 }
71 
72 // generate random char
73 static inline char
74 randc() {
75  return CHARSET[rng(0, CHARSET_LEN - 1)];
76 }
77 
78 // generate random string of desired length, MUST FREE STR!
79 static inline char*
80 rands(size_t len) {
81  char *str = (char*)malloc(len + 1);
82 
83  size_t i;
84  for(i=0;i<len;i++) {
85  str[i] = randc();
86  }
87  str[len+1] = '\0';
88 
89  return str;
90 }
91 
92 #endif
New functions and types related to string and string manipulation.