KCoreAddons

krandom.cpp
1 /*
2  This file is part of the KDE libraries
3 
4  SPDX-FileCopyrightText: 1999 Matthias Kalle Dalheimer <[email protected]>
5  SPDX-FileCopyrightText: 2000 Charles Samuels <[email protected]>
6  SPDX-FileCopyrightText: 2005 Joseph Wenninger <[email protected]>
7 
8  SPDX-License-Identifier: LGPL-2.0-or-later
9 */
10 
11 #include "krandom.h"
12 
13 #include <stdlib.h>
14 #ifdef Q_OS_WIN
15 #include <process.h>
16 #else // Q_OS_WIN
17 #include <unistd.h>
18 #endif // Q_OS_WIN
19 #include <stdio.h>
20 #include <time.h>
21 #ifndef Q_OS_WIN
22 #include <sys/time.h>
23 #endif // Q_OS_WIN
24 #include <fcntl.h>
25 
26 #include <QFile>
27 #include <QThread>
28 #include <QThreadStorage>
29 
31 {
32  static QThreadStorage<bool> initialized_threads;
33  if (!initialized_threads.localData()) {
34  unsigned int seed;
35  initialized_threads.setLocalData(true);
36  QFile urandom(QStringLiteral("/dev/urandom"));
37  bool opened = urandom.open(QIODevice::ReadOnly | QIODevice::Unbuffered);
38  if (!opened || urandom.read(reinterpret_cast<char *>(&seed), sizeof(seed)) != sizeof(seed)) {
39  // No /dev/urandom... try something else.
40  qsrand(getpid());
41  seed = qrand() ^ time(nullptr) ^ reinterpret_cast<quintptr>(QThread::currentThread());
42  }
43  qsrand(seed);
44  }
45  return qrand();
46 }
47 
49 {
50  if (length <= 0) {
51  return QString();
52  }
53 
54  QString str; str.resize(length);
55  int i = 0;
56  while (length--) {
57  int r = random() % 62;
58  r += 48;
59  if (r > 57) {
60  r += 7;
61  }
62  if (r > 90) {
63  r += 6;
64  }
65  str[i++] = char(r);
66  // so what if I work backwards?
67  }
68  return str;
69 }
KCOREADDONS_EXPORT int random()
Generates a uniform random number.
Definition: krandom.cpp:30
void setLocalData(T data)
void resize(int size)
qint64 read(char *data, qint64 maxSize)
virtual bool open(QIODevice::OpenMode mode) override
QThread * currentThread()
KCOREADDONS_EXPORT QString randomString(int length)
Generates a random string.
Definition: krandom.cpp:48
This file is part of the KDE documentation.
Documentation copyright © 1996-2020 The KDE developers.
Generated on Sun May 31 2020 23:11:13 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.