blob: bd24f2e50c1ab923f2b8a06bb065b833554ab68e [file] [log] [blame]
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00001//===-------------------------- random.cpp --------------------------------===//
2//
Howard Hinnantf5256e12010-05-11 21:36:01 +00003// The LLVM Compiler Infrastructure
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00004//
Howard Hinnantb64f8b02010-11-16 22:09:02 +00005// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00007//
8//===----------------------------------------------------------------------===//
9
Marshall Clowb8dd5ca2013-10-09 21:49:03 +000010#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
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000016#include "random"
17#include "system_error"
18
David Chisnall997e4542012-02-29 13:05:08 +000019#ifdef __sun__
20#define rename solaris_headers_are_broken
21#endif
Yaron Keren81241a92013-11-18 21:30:19 +000022#if !defined(_WIN32)
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000023#include <fcntl.h>
24#include <unistd.h>
Yaron Keren81241a92013-11-18 21:30:19 +000025#endif // defined(_WIN32)
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000026#include <errno.h>
27
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000028_LIBCPP_BEGIN_NAMESPACE_STD
29
Marshall Clowb8dd5ca2013-10-09 21:49:03 +000030#if defined(_WIN32)
31random_device::random_device(const string&)
32{
33}
34
35random_device::~random_device()
36{
37}
38
39unsigned
40random_device::operator()()
41{
42 unsigned r;
43 errno_t err = rand_s(&r);
44 if (err)
45 __throw_system_error(err, "random_device rand_s failed.");
46 return r;
47}
48#else
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000049random_device::random_device(const string& __token)
50 : __f_(open(__token.c_str(), O_RDONLY))
51{
52 if (__f_ <= 0)
53 __throw_system_error(errno, ("random_device failed to open " + __token).c_str());
54}
55
56random_device::~random_device()
57{
58 close(__f_);
59}
60
61unsigned
62random_device::operator()()
63{
64 unsigned r;
65 read(__f_, &r, sizeof(r));
66 return r;
67}
Marshall Clowb8dd5ca2013-10-09 21:49:03 +000068#endif // defined(_WIN32)
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000069
70double
Howard Hinnantc83960a2012-07-20 21:44:27 +000071random_device::entropy() const _NOEXCEPT
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000072{
73 return 0;
74}
75
76_LIBCPP_END_NAMESPACE_STD