1 //===----------------------------------------------------------------------===// 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 // <random> 11 12 // class random_device; 13 14 // explicit random_device(const string& token = implementation-defined); 15 16 // For the following ctors, the standard states: "The semantics and default 17 // value of the token parameter are implementation-defined". Implementations 18 // therefore aren't required to accept any string, but the default shouldn't 19 // throw. 20 21 #include <random> 22 #include <system_error> 23 #include <cassert> 24 25 #if !defined(_WIN32) 26 #include <unistd.h> 27 #endif 28 29 #include "test_macros.h" 30 31 is_valid_random_device(const std::string & token)32bool is_valid_random_device(const std::string &token) { 33 #if defined(_LIBCPP_USING_DEV_RANDOM) 34 // Not an exhaustive list: they're the only tokens that are tested below. 35 return token == "/dev/urandom" || token == "/dev/random"; 36 #else 37 return token == "/dev/urandom"; 38 #endif 39 } 40 check_random_device_valid(const std::string & token)41void check_random_device_valid(const std::string &token) { 42 std::random_device r(token); 43 } 44 check_random_device_invalid(const std::string & token)45void check_random_device_invalid(const std::string &token) { 46 #ifndef TEST_HAS_NO_EXCEPTIONS 47 try { 48 std::random_device r(token); 49 LIBCPP_ASSERT(false); 50 } catch (const std::system_error&) { 51 } 52 #else 53 ((void)token); 54 #endif 55 } 56 57 main()58int main() { 59 { 60 std::random_device r; 61 } 62 { 63 std::string token = "wrong file"; 64 check_random_device_invalid(token); 65 } 66 { 67 std::string token = "/dev/urandom"; 68 if (is_valid_random_device(token)) 69 check_random_device_valid(token); 70 else 71 check_random_device_invalid(token); 72 } 73 { 74 std::string token = "/dev/random"; 75 if (is_valid_random_device(token)) 76 check_random_device_valid(token); 77 else 78 check_random_device_invalid(token); 79 } 80 #if !defined(_WIN32) 81 // Test that random_device(const string&) properly handles getting 82 // a file descriptor with the value '0'. Do this by closing the standard 83 // streams so that the descriptor '0' is available. 84 { 85 int ec; 86 ec = close(STDIN_FILENO); 87 assert(!ec); 88 ec = close(STDOUT_FILENO); 89 assert(!ec); 90 ec = close(STDERR_FILENO); 91 assert(!ec); 92 std::random_device r; 93 } 94 #endif // !defined(_WIN32) 95 } 96