forked from CriztianiX/lua-resty-nanoid
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nanoid.h
108 lines (82 loc) · 2.3 KB
/
nanoid.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#ifndef __NANOID_H__
#define __NANOID_H__
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
// default alphabet list
// updated to nanoid 2.0
static char alphs[] = {
'-', '_',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'\0'
};
// custom alphabet pool and length
char* custom(char alphs[], int size);
// custom length
char* generate(int size);
// default character pool and 21 in length
char* simple();
// safe implementation of custom() which uses /dev/urandom
char* safe_custom(char alphs[], int size);
// safe implementation of generate()
char* safe_generate(int size);
// safe implementation of simple()
char* safe_simple();
char* custom(char alphs[], int size) {
int alph_size = strlen(alphs) - 1;
char *id = (char *) malloc(sizeof(char) * 3);
int i;
for(i = 0; i < size; i++ ) {
int random_num;
do {
random_num = rand();
} while (random_num >= (RAND_MAX - RAND_MAX % alph_size));
random_num %= alph_size;
id[i] = alphs[random_num];
}
return id;
}
char* generate(int size) {
return custom(alphs, size);
}
char* simple() {
return generate(21);
}
char* safe_custom(char alphs[], int size) {
char *buffer;
char *rand_buf;
unsigned int sum;
FILE *rand_src;
buffer = (char *) malloc(size);
rand_buf = (char *) malloc(size);
rand_src = fopen("/dev/urandom", "rb");
if (rand_src == NULL)
return NULL;
fread(buffer, size, 1, rand_src);
int i;
for (i = 0; i < size; ++i) {
sum += buffer[i];
}
free(buffer);
srand(sum);
int j;
for (j = 0; j < size; ++j) {
unsigned int random_num;
do {
random_num = rand();
} while (random_num >= (RAND_MAX - RAND_MAX % strlen(alphs)));
random_num %= strlen(alphs);
rand_buf[j] = alphs[random_num];
}
return rand_buf;
}
char* safe_generate(int size) {
return safe_custom(alphs, size);
}
char* safe_simple() {
return safe_generate(21);
}
#endif // __NANOID_H__