File: gen_id.c

package info (click to toggle)
mimedefang 2.71-3
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 1,932 kB
  • sloc: ansic: 8,798; perl: 6,504; sh: 1,624; tcl: 693; makefile: 73; php: 19
file content (45 lines) | stat: -rw-r--r-- 1,075 bytes parent folder | download | duplicates (6)
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
#include "mimedefang.h"
#include <pthread.h>

/* Our identifiers are in base-60 */
#define BASE 60

/* Our time-based identifier is 5 base-60 characters.
   TIMESPAN below is 60^5 */
#define TIMESPAN (BASE*BASE*BASE*BASE*BASE)

#define COUNTER_MOD (BASE*BASE)

/* Counter incremented each time gen_id is called */
static unsigned int id_counter = 0;

/* Mutext to protext id_counter */
static pthread_mutex_t id_counter_mutex = PTHREAD_MUTEX_INITIALIZER;

/* This had better be 60 characters long! */
static char const char_map[BASE] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX";

char *
gen_mx_id(char *out)
{
    unsigned int counter, time_part;
    int i;

    pthread_mutex_lock(&id_counter_mutex);
    counter = id_counter++;
    pthread_mutex_unlock(&id_counter_mutex);

    time_part = ((unsigned int) time(NULL)) % TIMESPAN;

    for (i=4; i>=0; i--) {
	out[i] = char_map[time_part % BASE];
	time_part /= BASE;
    }

    for (i=6; i>=5; i--) {
	out[i] = char_map[counter % BASE];
	counter /= BASE;
    }
    out[MX_ID_LEN] = 0;
    return out;
}