Updating for 1.0.2 release
[awesomized/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 return;
48
49 /* We free until we hit the null pair we stores during creation */
50 for (uint32_t x= 0; pairs[x].key; x++)
51 {
52 free(pairs[x].key);
53 if (pairs[x].value)
54 free(pairs[x].value);
55 }
56
57 free(pairs);
58 }
59
60 pairs_st *pairs_generate(uint64_t number_of, size_t value_length)
61 {
62 pairs_st *pairs= (pairs_st*)calloc((size_t)number_of + 1, sizeof(pairs_st));
63
64 if (pairs == NULL)
65 {
66 goto error;
67 }
68
69 for (uint64_t x= 0; x < number_of; x++)
70 {
71 pairs[x].key= (char *)calloc(100, sizeof(char));
72
73 if (pairs[x].key == NULL)
74 goto error;
75
76 get_random_string(pairs[x].key, 100);
77 pairs[x].key_length= 100;
78
79 if (value_length)
80 {
81 pairs[x].value= (char *)calloc(value_length, sizeof(char));
82
83 if (pairs[x].value == NULL)
84 goto error;
85
86 get_random_string(pairs[x].value, value_length);
87 pairs[x].value_length= value_length;
88 }
89 else
90 {
91 pairs[x].value= NULL;
92 pairs[x].value_length= 0;
93 }
94 }
95
96 return pairs;
97 error:
98 std::cerr << "Memory Allocation failure in pairs_generate." << std::endl;
99 exit(EXIT_SUCCESS);
100 }