generators.hpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2005-2009 Daniel James.
  2. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  3. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. // This uses std::rand to generate random values for tests.
  5. // Which is not good as different platforms will be running different tests.
  6. // It would be much better to use Boost.Random, but it doesn't
  7. // support all the compilers that I want to test on.
  8. #if !defined(BOOST_UNORDERED_TEST_HELPERS_GENERATORS_HEADER)
  9. #define BOOST_UNORDERED_TEST_HELPERS_GENERATORS_HEADER
  10. #include "./fwd.hpp"
  11. #include <boost/type_traits/add_const.hpp>
  12. #include <cstdlib>
  13. #include <stdexcept>
  14. #include <string>
  15. #include <utility>
  16. namespace test {
  17. struct seed_t
  18. {
  19. seed_t(unsigned int x)
  20. {
  21. using namespace std;
  22. srand(x);
  23. }
  24. };
  25. std::size_t random_value(std::size_t max)
  26. {
  27. using namespace std;
  28. return static_cast<std::size_t>(rand()) % max;
  29. }
  30. inline int generate(int const*, random_generator g)
  31. {
  32. using namespace std;
  33. int value = rand();
  34. if (g == limited_range) {
  35. value = value % 100;
  36. }
  37. return value;
  38. }
  39. inline char generate(char const*, random_generator)
  40. {
  41. using namespace std;
  42. return static_cast<char>((rand() >> 1) % (128 - 32) + 32);
  43. }
  44. inline signed char generate(signed char const*, random_generator)
  45. {
  46. using namespace std;
  47. return static_cast<signed char>(rand());
  48. }
  49. inline std::string generate(std::string const*, random_generator g)
  50. {
  51. using namespace std;
  52. char* char_ptr = 0;
  53. std::string result;
  54. if (g == limited_range) {
  55. std::size_t length = test::random_value(2) + 2;
  56. char const* strings[] = {"'vZh(3~ms", "%m", "_Y%U", "N'Y", "4,J_J"};
  57. for (std::size_t i = 0; i < length; ++i) {
  58. result += strings[random_value(sizeof(strings) / sizeof(strings[0]))];
  59. }
  60. } else {
  61. std::size_t length = test::random_value(10) + 1;
  62. for (std::size_t i = 0; i < length; ++i) {
  63. result += generate(char_ptr, g);
  64. }
  65. }
  66. return result;
  67. }
  68. float generate(float const*, random_generator g)
  69. {
  70. using namespace std;
  71. int x = 0;
  72. int value = generate(&x, g);
  73. return (float)value / (float)RAND_MAX;
  74. }
  75. }
  76. #endif