Merge from Trond
[m6w6/libmemcached] / clients / generator.c
1 #include "libmemcached/common.h"
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <stdint.h>
6 #include <string.h>
7
8 #include "generator.h"
9
10 /* Use this for string generation */
11 static const char ALPHANUMERICS[]=
12 "0123456789ABCDEFGHIJKLMNOPQRSTWXYZabcdefghijklmnopqrstuvwxyz";
13
14 #define ALPHANUMERICS_SIZE (sizeof(ALPHANUMERICS)-1)
15
16 static size_t get_alpha_num(void)
17 {
18 return (size_t)random() % ALPHANUMERICS_SIZE;
19 }
20
21 static void get_random_string(char *buffer, size_t size)
22 {
23 char *buffer_ptr= buffer;
24
25 while (--size)
26 *buffer_ptr++= ALPHANUMERICS[get_alpha_num()];
27 *buffer_ptr++= ALPHANUMERICS[get_alpha_num()];
28 }
29
30 void pairs_free(pairs_st *pairs)
31 {
32 uint32_t x;
33
34 if (!pairs)
35 return;
36
37 /* We free until we hit the null pair we stores during creation */
38 for (x= 0; pairs[x].key; x++)
39 {
40 free(pairs[x].key);
41 free(pairs[x].value);
42 }
43
44 free(pairs);
45 }
46
47 pairs_st *pairs_generate(uint64_t number_of, size_t value_length)
48 {
49 unsigned int x;
50 pairs_st *pairs;
51
52 pairs= (pairs_st*)calloc((size_t)number_of + 1, sizeof(pairs_st));
53
54 if (!pairs)
55 goto error;
56
57 for (x= 0; x < number_of; x++)
58 {
59 pairs[x].key= (char *)calloc(100, sizeof(char));
60 if (!pairs[x].key)
61 goto error;
62 get_random_string(pairs[x].key, 100);
63 pairs[x].key_length= 100;
64
65 pairs[x].value= (char *)calloc(value_length, sizeof(char));
66 if (!pairs[x].value)
67 goto error;
68 get_random_string(pairs[x].value, value_length);
69 pairs[x].value_length= value_length;
70 }
71
72 return pairs;
73 error:
74 fprintf(stderr, "Memory Allocation failure in pairs_generate.\n");
75 exit(0);
76 }