Merge lp:~tangent-org/libmemcached/1.0-build/ Build: jenkins-Libmemcached-187
[m6w6/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 /* Use this for string generation */
26 static const char ALPHANUMERICS[]=
27 "0123456789ABCDEFGHIJKLMNOPQRSTWXYZabcdefghijklmnopqrstuvwxyz";
28
29 #define ALPHANUMERICS_SIZE (sizeof(ALPHANUMERICS)-1)
30
31 static size_t get_alpha_num(void)
32 {
33 return (size_t)random() % ALPHANUMERICS_SIZE;
34 }
35
36 void get_random_string(char *buffer, size_t size)
37 {
38 char *buffer_ptr= buffer;
39
40 while (--size)
41 {
42 *buffer_ptr++= ALPHANUMERICS[get_alpha_num()];
43 }
44 *buffer_ptr++= ALPHANUMERICS[get_alpha_num()];
45 }
46
47 void pairs_free(pairs_st *pairs)
48 {
49 if (pairs == NULL)
50 {
51 return;
52 }
53
54 /* We free until we hit the null pair we stores during creation */
55 for (uint32_t x= 0; pairs[x].key; x++)
56 {
57 free(pairs[x].key);
58 if (pairs[x].value)
59 {
60 free(pairs[x].value);
61 }
62 }
63
64 free(pairs);
65 }
66
67 pairs_st *pairs_generate(uint64_t number_of, size_t value_length)
68 {
69 pairs_st *pairs= (pairs_st*)calloc((size_t)number_of + 1, sizeof(pairs_st));
70
71 if (pairs == NULL)
72 {
73 goto error;
74 }
75
76 for (uint64_t x= 0; x < number_of; x++)
77 {
78 pairs[x].key= (char *)calloc(100, sizeof(char));
79
80 if (pairs[x].key == NULL)
81 goto error;
82
83 get_random_string(pairs[x].key, 100);
84 pairs[x].key_length= 100;
85
86 if (value_length)
87 {
88 pairs[x].value= (char *)calloc(value_length, sizeof(char));
89
90 if (pairs[x].value == NULL)
91 goto error;
92
93 get_random_string(pairs[x].value, value_length);
94 pairs[x].value_length= value_length;
95 }
96 else
97 {
98 pairs[x].value= NULL;
99 pairs[x].value_length= 0;
100 }
101 }
102
103 return pairs;
104 error:
105 std::cerr << "Memory Allocation failure in pairs_generate." << std::endl;
106 exit(EXIT_SUCCESS);
107 }