m4: ax_assert
[awesomized/libmemcached] / clients / generator.cc
1 /* LibMemcached
2 * Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/
3 * Copyright (C) 2006-2009 Brian Aker
4 * All rights reserved.
5 *
6 * Use and distribution licensed under the BSD license. See
7 * the COPYING file in the parent directory for full text.
8 *
9 * Summary:
10 *
11 */
12
13 #include <mem_config.h>
14
15 #include <stdint.h>
16
17 #include <cstdio>
18 #include <cstdlib>
19 #include <cstring>
20 #include <iostream>
21 #include <unistd.h>
22
23 #include "clients/generator.h"
24
25 #define KEY_BYTES 20
26
27 /* Use this for string generation */
28 static const char ALPHANUMERICS[]=
29 "0123456789ABCDEFGHIJKLMNOPQRSTWXYZabcdefghijklmnopqrstuvwxyz";
30
31 #define ALPHANUMERICS_SIZE (sizeof(ALPHANUMERICS)-1)
32
33 static size_t get_alpha_num(void)
34 {
35 return (size_t)random() % ALPHANUMERICS_SIZE;
36 }
37
38 void get_random_string(char *buffer, size_t size)
39 {
40 char *buffer_ptr= buffer;
41
42 while (--size)
43 {
44 *buffer_ptr++= ALPHANUMERICS[get_alpha_num()];
45 }
46 *buffer_ptr++= ALPHANUMERICS[get_alpha_num()];
47 }
48
49 void pairs_free(pairs_st *pairs)
50 {
51 if (pairs == NULL)
52 {
53 return;
54 }
55
56 /* We free until we hit the null pair we stores during creation */
57 for (uint32_t x= 0; pairs[x].key; x++)
58 {
59 free(pairs[x].key);
60 if (pairs[x].value)
61 {
62 free(pairs[x].value);
63 }
64 }
65
66 free(pairs);
67 }
68
69 pairs_st *pairs_generate(uint64_t number_of, size_t value_length)
70 {
71 pairs_st *pairs= (pairs_st*)calloc((size_t)number_of + 1, sizeof(pairs_st));
72
73 if (pairs == NULL)
74 {
75 goto error;
76 }
77
78 for (uint64_t x= 0; x < number_of; x++)
79 {
80 pairs[x].key= (char *)calloc(KEY_BYTES, sizeof(char));
81
82 if (pairs[x].key == NULL)
83 goto error;
84
85 get_random_string(pairs[x].key, KEY_BYTES);
86 pairs[x].key_length= KEY_BYTES;
87
88 if (value_length)
89 {
90 pairs[x].value= (char *)calloc(value_length, sizeof(char));
91
92 if (pairs[x].value == NULL)
93 goto error;
94
95 get_random_string(pairs[x].value, value_length);
96 pairs[x].value_length= value_length;
97 }
98 else
99 {
100 pairs[x].value= NULL;
101 pairs[x].value_length= 0;
102 }
103 }
104
105 return pairs;
106 error:
107 std::cerr << "Memory Allocation failure in pairs_generate." << std::endl;
108 exit(EXIT_SUCCESS);
109 }