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 <QRandomGenerator>
28 #include <QThread>
29 #include <QThreadStorage>
30 
31 #if KCOREADDONS_BUILD_DEPRECATED_SINCE(5, 72)
33 {
34  static QThreadStorage<bool> initialized_threads;
35  if (!initialized_threads.localData()) {
36  unsigned int seed;
37  initialized_threads.setLocalData(true);
38  QFile urandom(QStringLiteral("/dev/urandom"));
39  bool opened = urandom.open(QIODevice::ReadOnly | QIODevice::Unbuffered);
40  if (!opened || urandom.read(reinterpret_cast<char *>(&seed), sizeof(seed)) != sizeof(seed)) {
41 // silence warnings about use of deprecated qsrand()/qrand()
42 // Porting to QRandomGenerator::global() instead might result in no new seed set for the generator behind qrand()
43 // which then might affect other places indirectly relying on this.
44 // So just keeping the old calls here, as this method is also deprecated and will disappear together with qsrand/qrand.
45 QT_WARNING_PUSH
46 QT_WARNING_DISABLE_CLANG("-Wdeprecated-declarations")
47 QT_WARNING_DISABLE_GCC("-Wdeprecated-declarations")
48  // No /dev/urandom... try something else.
49  qsrand(getpid());
50  seed = qrand() ^ time(nullptr) ^ reinterpret_cast<quintptr>(QThread::currentThread());
51  }
52  qsrand(seed);
53  }
54  return qrand();
55 QT_WARNING_POP
56 }
57 #endif
58 
60 {
61  if (length <= 0) {
62  return QString();
63  }
64 
65  QString str; 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++] = 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:32
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:59
This file is part of the KDE documentation.
Documentation copyright © 1996-2020 The KDE developers.
Generated on Wed Aug 12 2020 23:01:56 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.