0.9.8.10
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
DataGeneratorRandom.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2007-2015 Hypertable, Inc.
3  *
4  * This file is part of Hypertable.
5  *
6  * Hypertable is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; version 3 of the
9  * License, or any later version.
10  *
11  * Hypertable is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19  * 02110-1301, USA.
20  */
21 
22 #include <Common/Compat.h>
23 
24 #include "DataGeneratorRandom.h"
25 
26 #include <cassert>
27 #include <random>
28 
29 namespace {
30  const char cb64[] =
31  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
32  std::mt19937 g_engine {1};
33 }
34 
35 int32_t Hypertable::random_int32(int32_t maximum) {
36  assert(maximum > 0);
37  return std::uniform_int_distribution<int32_t>(0, maximum-1)(g_engine);
38 }
39 
41  g_engine.seed(seed);
42 }
43 
44 void Hypertable::random_fill_with_chars(char *buf, size_t len,
45  const char *charset) {
46  size_t in_i = 0, out_i = 0;
47  uint32_t u32;
48  uint8_t *in;
49  const char *chars;
50 
51  if (charset)
52  chars = charset;
53  else
54  chars = cb64;
55  size_t set_len = strlen(chars);
56 
57  assert(set_len > 0 && set_len <= 256);
58 
59  while (out_i < len) {
60  u32 = std::uniform_int_distribution<uint32_t>()(g_engine);
61  in = (uint8_t *)&u32;
62 
63  in_i = 0;
64  buf[out_i++] = chars[in[in_i] % set_len];
65  if (out_i == len)
66  break;
67 
68  in_i++;
69  buf[out_i++] = chars[in[in_i] % set_len];
70  if (out_i == len)
71  break;
72 
73  in_i++;
74  buf[out_i++] = chars[in[in_i] % set_len];
75  if (out_i == len)
76  break;
77 
78  in_i++;
79  buf[out_i++] = chars[in[in_i] % set_len];
80  }
81 }
int32_t random_int32(int32_t maximum)
Generate random 32-bit integer.
Compatibility Macros for C/C++.
void random_fill_with_chars(char *buf, size_t len, const char *charset=nullptr)
Fills a buffer with random values from a set of characters.
void random_generator_set_seed(unsigned seed)
Sets random number generator seed.