xref: /llvm-project-15.0.7/libcxx/src/random.cpp (revision 3a9632d5)
1 //===-------------------------- random.cpp --------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #if defined(_WIN32)
11 // Must be defined before including stdlib.h to enable rand_s().
12 #define _CRT_RAND_S
13 #include <stdio.h>
14 #endif
15 
16 #include "random"
17 #include "system_error"
18 
19 #ifdef __sun__
20 #define rename solaris_headers_are_broken
21 #endif
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <errno.h>
25 
26 _LIBCPP_BEGIN_NAMESPACE_STD
27 
28 #if defined(_WIN32)
29 random_device::random_device(const string&)
30 {
31 }
32 
33 random_device::~random_device()
34 {
35 }
36 
37 unsigned
38 random_device::operator()()
39 {
40     unsigned r;
41     errno_t err = rand_s(&r);
42     if (err)
43         __throw_system_error(err, "random_device rand_s failed.");
44     return r;
45 }
46 #else
47 random_device::random_device(const string& __token)
48     : __f_(open(__token.c_str(), O_RDONLY))
49 {
50     if (__f_ <= 0)
51         __throw_system_error(errno, ("random_device failed to open " + __token).c_str());
52 }
53 
54 random_device::~random_device()
55 {
56     close(__f_);
57 }
58 
59 unsigned
60 random_device::operator()()
61 {
62     unsigned r;
63     read(__f_, &r, sizeof(r));
64     return r;
65 }
66 #endif // defined(_WIN32)
67 
68 double
69 random_device::entropy() const _NOEXCEPT
70 {
71     return 0;
72 }
73 
74 _LIBCPP_END_NAMESPACE_STD
75