1 // Unit test for boost::lexical_cast.
2 //
3 // See http://www.boost.org for most recent version, including documentation.
4 //
5 // Copyright Antony Polukhin, 2012-2019.
6 //
7 // Distributed under the Boost
8 // Software License, Version 1.0. (See accompanying file
9 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
10
11 #include <boost/config.hpp>
12
13 #if defined(__INTEL_COMPILER)
14 #pragma warning(disable: 193 383 488 981 1418 1419)
15 #elif defined(BOOST_MSVC)
16 #pragma warning(disable: 4097 4100 4121 4127 4146 4244 4245 4511 4512 4701 4800)
17 #endif
18
19 #include <boost/lexical_cast.hpp>
20 #include <boost/core/lightweight_test.hpp>
21 #include <boost/range/iterator_range.hpp>
22
23 #include <cstdlib>
24
25 #ifndef BOOST_NO_EXCEPTIONS
26 #error "This test must be compiled with -DBOOST_NO_EXCEPTIONS"
27 #endif
28
29 struct Escape
30 {
EscapeEscape31 Escape(){}
EscapeEscape32 Escape(const std::string& s)
33 : str_(s)
34 {}
35
36 std::string str_;
37 };
38
operator <<(std::ostream & o,const Escape & rhs)39 inline std::ostream& operator<< (std::ostream& o, const Escape& rhs)
40 {
41 return o << rhs.str_;
42 }
43
operator >>(std::istream & i,Escape & rhs)44 inline std::istream& operator>> (std::istream& i, Escape& rhs)
45 {
46 return i >> rhs.str_;
47 }
48
49 namespace boost {
50
throw_exception(std::exception const &)51 BOOST_NORETURN void throw_exception(std::exception const & ) {
52 static int state = 0;
53 ++ state;
54
55 Escape v("");
56 switch(state) {
57 case 1:
58 lexical_cast<char>(v); // should call boost::throw_exception
59 std::exit(1);
60 case 2:
61 lexical_cast<unsigned char>(v); // should call boost::throw_exception
62 std::exit(2);
63 }
64 std::exit(boost::report_errors());
65 }
66
67 }
68
test_exceptions_off()69 void test_exceptions_off() {
70 using namespace boost;
71 Escape v("");
72
73 v = lexical_cast<Escape>(100);
74 BOOST_TEST_EQ(lexical_cast<int>(v), 100);
75 BOOST_TEST_EQ(lexical_cast<unsigned int>(v), 100u);
76
77 v = lexical_cast<Escape>(0.0);
78 BOOST_TEST_EQ(lexical_cast<double>(v), 0.0);
79
80 BOOST_TEST_EQ(lexical_cast<short>(100), 100);
81 BOOST_TEST_EQ(lexical_cast<float>(0.0), 0.0);
82
83 lexical_cast<short>(700000); // should call boost::throw_exception
84 BOOST_TEST(false);
85 }
86
main()87 int main() {
88 test_exceptions_off();
89
90 return boost::report_errors();
91 }
92
93