1 | // Copyright 2019 Peter Dimov |
2 | // |
3 | // Distributed under the Boost Software License, Version 1.0. |
4 | // http://www.boost.org/LICENSE_1_0.txt |
5 | |
6 | #include <boost/endian/detail/order.hpp> |
7 | #include <boost/core/lightweight_test.hpp> |
8 | #include <boost/config.hpp> |
9 | #include <boost/cstdint.hpp> |
10 | #include <cstddef> |
11 | #include <ostream> |
12 | #include <iomanip> |
13 | |
14 | #if defined(_MSC_VER) |
15 | # pragma warning(disable: 4127) // conditional expression is constant |
16 | #endif |
17 | |
18 | class byte_span |
19 | { |
20 | private: |
21 | |
22 | unsigned char const * p_; |
23 | std::size_t n_; |
24 | |
25 | public: |
26 | |
27 | byte_span( unsigned char const * p, std::size_t n ): p_( p ), n_( n ) |
28 | { |
29 | } |
30 | |
31 | template<std::size_t N> explicit byte_span( unsigned char const (&a)[ N ] ): p_( a ), n_( N ) |
32 | { |
33 | } |
34 | |
35 | bool operator==( byte_span const& r ) const |
36 | { |
37 | if( n_ != r.n_ ) return false; |
38 | |
39 | for( std::size_t i = 0; i < n_; ++i ) |
40 | { |
41 | if( p_[ i ] != r.p_[ i ] ) return false; |
42 | } |
43 | |
44 | return true; |
45 | } |
46 | |
47 | friend std::ostream& operator<<( std::ostream& os, byte_span s ) |
48 | { |
49 | if( s.n_ == 0 ) return os; |
50 | |
51 | os << std::hex << std::setfill( '0' ) << std::uppercase; |
52 | |
53 | os << std::setw( 2 ) << +s.p_[ 0 ]; |
54 | |
55 | for( std::size_t i = 1; i < s.n_; ++i ) |
56 | { |
57 | os << ':' << std::setw( 2 ) << +s.p_[ i ]; |
58 | } |
59 | |
60 | os << std::dec << std::setfill( ' ' ) << std::nouppercase; |
61 | |
62 | return os; |
63 | } |
64 | }; |
65 | |
66 | int main() |
67 | { |
68 | boost::uint64_t v = static_cast<boost::uint64_t>( 0x0102030405060708ull ); |
69 | byte_span v2( reinterpret_cast<unsigned char const*>( &v ), sizeof(v) ); |
70 | |
71 | if( boost::endian::order::native == boost::endian::order::little ) |
72 | { |
73 | unsigned char w[] = { 8, 7, 6, 5, 4, 3, 2, 1 }; |
74 | BOOST_TEST_EQ( v2, byte_span( w ) ); |
75 | } |
76 | else if( boost::endian::order::native == boost::endian::order::big ) |
77 | { |
78 | unsigned char w[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; |
79 | BOOST_TEST_EQ( v2, byte_span( w ) ); |
80 | } |
81 | else |
82 | { |
83 | BOOST_ERROR( "boost::endian::order::native is neither big nor little" ); |
84 | } |
85 | |
86 | return boost::report_errors(); |
87 | } |
88 | |