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