error_category_test.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2018 Peter Dimov.
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. //
  5. // See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt
  7. // See library home page at http://www.boost.org/libs/system
  8. // Avoid spurious VC++ warnings
  9. # define _CRT_SECURE_NO_WARNINGS
  10. #include <boost/system/error_code.hpp>
  11. #include <boost/core/lightweight_test.hpp>
  12. #include <cstdio>
  13. //
  14. namespace sys = boost::system;
  15. class user_category: public sys::error_category
  16. {
  17. public:
  18. virtual const char * name() const BOOST_NOEXCEPT
  19. {
  20. return "user";
  21. }
  22. virtual std::string message( int ev ) const
  23. {
  24. char buffer[ 256 ];
  25. std::sprintf( buffer, "user message %d", ev );
  26. return buffer;
  27. }
  28. using sys::error_category::message;
  29. };
  30. static user_category s_cat_1;
  31. static user_category s_cat_2;
  32. int main()
  33. {
  34. // default_error_condition
  35. BOOST_TEST( s_cat_1.default_error_condition( 1 ) == sys::error_condition( 1, s_cat_1 ) );
  36. BOOST_TEST( s_cat_2.default_error_condition( 2 ) == sys::error_condition( 2, s_cat_2 ) );
  37. // equivalent
  38. BOOST_TEST( s_cat_1.equivalent( 1, sys::error_condition( 1, s_cat_1 ) ) );
  39. BOOST_TEST( !s_cat_1.equivalent( 1, sys::error_condition( 2, s_cat_1 ) ) );
  40. BOOST_TEST( !s_cat_1.equivalent( 1, sys::error_condition( 2, s_cat_2 ) ) );
  41. // the other equivalent
  42. BOOST_TEST( s_cat_1.equivalent( sys::error_code( 1, s_cat_1 ), 1 ) );
  43. BOOST_TEST( !s_cat_1.equivalent( sys::error_code( 1, s_cat_1 ), 2 ) );
  44. BOOST_TEST( !s_cat_1.equivalent( sys::error_code( 1, s_cat_2 ), 1 ) );
  45. // message
  46. {
  47. char buffer[ 256 ];
  48. BOOST_TEST_CSTR_EQ( s_cat_1.message( 1, buffer, sizeof( buffer ) ), s_cat_1.message( 1 ).c_str() );
  49. }
  50. {
  51. char buffer[ 4 ];
  52. BOOST_TEST_CSTR_EQ( s_cat_1.message( 1, buffer, sizeof( buffer ) ), "use" );
  53. }
  54. // ==
  55. BOOST_TEST_NOT( s_cat_1 == s_cat_2 );
  56. BOOST_TEST( s_cat_1 != s_cat_2 );
  57. return boost::report_errors();
  58. }