1 | // (C) Copyright 2018 Mario Suvajac |
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 | |
5 | // See http://www.boost.org/libs/iostreams for documentation. |
6 | |
7 | #include <boost/iostreams/detail/adapter/non_blocking_adapter.hpp> |
8 | #include <boost/iterator/counting_iterator.hpp> |
9 | #include <boost/test/unit_test.hpp> |
10 | #include <boost/iostreams/categories.hpp> |
11 | |
12 | #include <algorithm> |
13 | |
14 | // Source that reads only one byte every time read() is called. |
15 | class read_one_source |
16 | { |
17 | public: |
18 | typedef char char_type; |
19 | typedef boost::iostreams::source_tag category; |
20 | |
21 | template <std::size_t N> |
22 | read_one_source(const char (&data)[N]) |
23 | : data_size_m(N), data_m(data), pos_m(0) |
24 | { |
25 | } |
26 | |
27 | std::streamsize read(char* s, std::streamsize n) |
28 | { |
29 | if (pos_m < data_size_m && n > 0) |
30 | { |
31 | *s = data_m[pos_m++]; |
32 | return 1; |
33 | } |
34 | else |
35 | { |
36 | return -1; |
37 | } |
38 | } |
39 | |
40 | private: |
41 | std::size_t data_size_m; |
42 | const char* data_m; |
43 | std::size_t pos_m; |
44 | }; |
45 | |
46 | void nonblocking_read_test() |
47 | { |
48 | static const int data_size_k = 100; |
49 | |
50 | char data[data_size_k]; |
51 | std::copy(first: boost::counting_iterator<char>(0), |
52 | last: boost::counting_iterator<char>(data_size_k), |
53 | result: data); |
54 | |
55 | read_one_source src(data); |
56 | boost::iostreams::non_blocking_adapter<read_one_source> nb(src); |
57 | |
58 | char read_data[data_size_k]; |
59 | std::streamsize amt = boost::iostreams::read(t&: nb, s: read_data, n: data_size_k); |
60 | |
61 | BOOST_CHECK_EQUAL(amt, data_size_k); |
62 | |
63 | for (int i = 0; i < data_size_k; ++i) |
64 | { |
65 | BOOST_CHECK_EQUAL(std::char_traits<char>::to_int_type(read_data[i]), i); |
66 | } |
67 | } |
68 | |
69 | boost::unit_test::test_suite* init_unit_test_suite(int, char* []) |
70 | { |
71 | boost::unit_test::test_suite* test = BOOST_TEST_SUITE("non-blocking read test" ); |
72 | test->add(BOOST_TEST_CASE(&nonblocking_read_test)); |
73 | return test; |
74 | } |
75 | |