Made the memcached_string stuff private, but still testable.
[m6w6/libmemcached] / clients / generator.c
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 "libmemcached/common.h"
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <stdint.h>
17 #include <string.h>
18
19 #include "generator.h"
20
21 /* Use this for string generation */
22 static const char ALPHANUMERICS[]=
23 "0123456789ABCDEFGHIJKLMNOPQRSTWXYZabcdefghijklmnopqrstuvwxyz";
24
25 #define ALPHANUMERICS_SIZE (sizeof(ALPHANUMERICS)-1)
26
27 static size_t get_alpha_num(void)
28 {
29 return (size_t)random() % ALPHANUMERICS_SIZE;
30 }
31
32 static void get_random_string(char *buffer, size_t size)
33 {
34 char *buffer_ptr= buffer;
35
36 while (--size)
37 *buffer_ptr++= ALPHANUMERICS[get_alpha_num()];
38 *buffer_ptr++= ALPHANUMERICS[get_alpha_num()];
39 }
40
41 void pairs_free(pairs_st *pairs)
42 {
43 uint32_t x;
44
45 if (!pairs)
46 return;
47
48 /* We free until we hit the null pair we stores during creation */
49 for (x= 0; pairs[x].key; x++)
50 {
51 free(pairs[x].key);
52 free(pairs[x].value);
53 }
54
55 free(pairs);
56 }
57
58 pairs_st *pairs_generate(uint64_t number_of, size_t value_length)
59 {
60 unsigned int x;
61 pairs_st *pairs;
62
63 pairs= (pairs_st*)calloc((size_t)number_of + 1, sizeof(pairs_st));
64
65 if (!pairs)
66 goto error;
67
68 for (x= 0; x < number_of; x++)
69 {
70 pairs[x].key= (char *)calloc(100, sizeof(char));
71 if (!pairs[x].key)
72 goto error;
73 get_random_string(pairs[x].key, 100);
74 pairs[x].key_length= 100;
75
76 pairs[x].value= (char *)calloc(value_length, sizeof(char));
77 if (!pairs[x].value)
78 goto error;
79 get_random_string(pairs[x].value, value_length);
80 pairs[x].value_length= value_length;
81 }
82
83 return pairs;
84 error:
85 fprintf(stderr, "Memory Allocation failure in pairs_generate.\n");
86 exit(0);
87 }