Update all of libtest around runner.
[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 {
57 free(pairs[x].value);
58 }
59 }
60
61 free(pairs);
62 }
63
64 pairs_st *pairs_generate(uint64_t number_of, size_t value_length)
65 {
66 pairs_st *pairs= (pairs_st*)calloc((size_t)number_of + 1, sizeof(pairs_st));
67
68 if (pairs == NULL)
69 {
70 goto error;
71 }
72
73 for (uint64_t x= 0; x < number_of; x++)
74 {
75 pairs[x].key= (char *)calloc(100, sizeof(char));
76
77 if (pairs[x].key == NULL)
78 goto error;
79
80 get_random_string(pairs[x].key, 100);
81 pairs[x].key_length= 100;
82
83 if (value_length)
84 {
85 pairs[x].value= (char *)calloc(value_length, sizeof(char));
86
87 if (pairs[x].value == NULL)
88 goto error;
89
90 get_random_string(pairs[x].value, value_length);
91 pairs[x].value_length= value_length;
92 }
93 else
94 {
95 pairs[x].value= NULL;
96 pairs[x].value_length= 0;
97 }
98 }
99
100 return pairs;
101 error:
102 std::cerr << "Memory Allocation failure in pairs_generate." << std::endl;
103 exit(EXIT_SUCCESS);
104 }