testing: tsan
[m6w6/libmemcached] / src / bin / common / generator.cc
1 /*
2 +--------------------------------------------------------------------+
3 | libmemcached - C/C++ Client Library for memcached |
4 +--------------------------------------------------------------------+
5 | Redistribution and use in source and binary forms, with or without |
6 | modification, are permitted under the terms of the BSD license. |
7 | You should have received a copy of the license in a bundled file |
8 | named LICENSE; in case you did not receive a copy you can review |
9 | the terms online at: https://opensource.org/licenses/BSD-3-Clause |
10 +--------------------------------------------------------------------+
11 | Copyright (c) 2006-2014 Brian Aker https://datadifferential.com/ |
12 | Copyright (c) 2020 Michael Wallner <mike@php.net> |
13 +--------------------------------------------------------------------+
14 */
15
16 #include "mem_config.h"
17
18 #include <stdint.h>
19
20 #include <cstdio>
21 #include <cstdlib>
22 #include <cstring>
23 #include <iostream>
24 #include <unistd.h>
25
26 #include "generator.h"
27
28 #define KEY_BYTES 20
29
30 /* Use this for string generation */
31 static const char ALPHANUMERICS[] = "0123456789ABCDEFGHIJKLMNOPQRSTWXYZabcdefghijklmnopqrstuvwxyz";
32
33 #define ALPHANUMERICS_SIZE (sizeof(ALPHANUMERICS) - 1)
34
35 static size_t get_alpha_num(void) {
36 return (size_t) random() % ALPHANUMERICS_SIZE;
37 }
38
39 void get_random_string(char *buffer, size_t size) {
40 char *buffer_ptr = buffer;
41
42 while (--size) {
43 *buffer_ptr++ = ALPHANUMERICS[get_alpha_num()];
44 }
45 *buffer_ptr++ = ALPHANUMERICS[get_alpha_num()];
46 }
47
48 void pairs_free(pairs_st *pairs) {
49 if (pairs == NULL) {
50 return;
51 }
52
53 /* We free until we hit the null pair we stores during creation */
54 for (uint32_t x = 0; pairs[x].key; x++) {
55 free(pairs[x].key);
56 if (pairs[x].value) {
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 pairs_st *pairs = (pairs_st *) calloc((size_t) number_of + 1, sizeof(pairs_st));
66
67 if (pairs == NULL) {
68 goto error;
69 }
70
71 for (uint64_t x = 0; x < number_of; x++) {
72 pairs[x].key = (char *) calloc(KEY_BYTES, sizeof(char));
73
74 if (pairs[x].key == NULL)
75 goto error;
76
77 get_random_string(pairs[x].key, KEY_BYTES);
78 pairs[x].key_length = KEY_BYTES;
79
80 if (value_length) {
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 } else {
89 pairs[x].value = NULL;
90 pairs[x].value_length = 0;
91 }
92 }
93
94 return pairs;
95 error:
96 std::cerr << "Memory Allocation failure in pairs_generate." << std::endl;
97 exit(EXIT_SUCCESS);
98 }