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 
30 #if KCOREADDONS_BUILD_DEPRECATED_SINCE(5, 72)
32 {
33  static QThreadStorage<bool> initialized_threads;
34  if (!initialized_threads.localData()) {
35  unsigned int seed;
36  initialized_threads.setLocalData(true);
37  QFile urandom(QStringLiteral("/dev/urandom"));
38  bool opened = urandom.open(QIODevice::ReadOnly | QIODevice::Unbuffered);
39  if (!opened || urandom.read(reinterpret_cast<char *>(&seed), sizeof(seed)) != sizeof(seed)) {
40  // silence warnings about use of deprecated qsrand()/qrand()
41  // Porting to QRandomGenerator::global() instead might result in no new seed set for the generator behind qrand()
42  // which then might affect other places indirectly relying on this.
43  // So just keeping the old calls here, as this method is also deprecated and will disappear together with qsrand/qrand.
44  QT_WARNING_PUSH
45  QT_WARNING_DISABLE_CLANG("-Wdeprecated-declarations")
46  QT_WARNING_DISABLE_GCC("-Wdeprecated-declarations")
47  // No /dev/urandom... try something else.
48  qsrand(getpid());
49  seed = qrand() ^ time(nullptr) ^ reinterpret_cast<quintptr>(QThread::currentThread());
50  }
51  qsrand(seed);
52  }
53  return qrand();
54  QT_WARNING_POP
55 }
56 #endif
57 
59 {
60  if (length <= 0) {
61  return QString();
62  }
63 
64  QString str;
65  str.resize(length);
66  int i = 0;
67  while (length--) {
68  int r = QRandomGenerator::global()->bounded(62);
69  r += 48;
70  if (r > 57) {
71  r += 7;
72  }
73  if (r > 90) {
74  r += 6;
75  }
76  str[i++] = QLatin1Char(char(r));
77  // so what if I work backwards?
78  }
79  return str;
80 }
KCOREADDONS_EXPORT int random()
Generates a uniform random number.
Definition: krandom.cpp:31
void setLocalData(T data)
void resize(int size)
qint64 read(char *data, qint64 maxSize)
virtual bool open(QIODevice::OpenMode mode) override
double bounded(double highest)
QThread * currentThread()
QRandomGenerator * global()
KCOREADDONS_EXPORT QString randomString(int length)
Generates a random string.
Definition: krandom.cpp:58
This file is part of the KDE documentation.
Documentation copyright © 1996-2021 The KDE developers.
Generated on Sat Apr 10 2021 23:01:55 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.