summaryrefslogtreecommitdiffstats
path: root/src/boost/libs/iostreams/test/read_nonblocking_test.cpp
blob: 64a71951fed28af6df3b7ecdb1fe31a70a633e20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// (C) Copyright 2018 Mario Suvajac
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)

// See http://www.boost.org/libs/iostreams for documentation.

#include <boost/iostreams/detail/adapter/non_blocking_adapter.hpp>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/iostreams/categories.hpp>

#include <algorithm>

// Source that reads only one byte every time read() is called.
class read_one_source
{
public:
    typedef char                         char_type;
    typedef boost::iostreams::source_tag category;

    template <std::size_t N>
    read_one_source(const char (&data)[N])
        : data_size_m(N), data_m(data), pos_m(0)
    {
    }

    std::streamsize read(char* s, std::streamsize n)
    {
        if (pos_m < data_size_m && n > 0)
        {
            *s = data_m[pos_m++];
            return 1;
        }
        else
        {
            return -1;
        }
    }

private:
    std::size_t data_size_m;
    const char* data_m;
    std::size_t pos_m;
};

void nonblocking_read_test()
{
    static const int data_size_k = 100;

    char data[data_size_k];
    std::copy(boost::counting_iterator<char>(0),
              boost::counting_iterator<char>(data_size_k),
              data);

    read_one_source src(data);
    boost::iostreams::non_blocking_adapter<read_one_source> nb(src);

    char read_data[data_size_k];
    std::streamsize amt = boost::iostreams::read(nb, read_data, data_size_k);

    BOOST_CHECK_EQUAL(amt, data_size_k);

    for (int i = 0; i < data_size_k; ++i)
    {
        BOOST_CHECK_EQUAL(std::char_traits<char>::to_int_type(read_data[i]), i);
    }
}

boost::unit_test::test_suite* init_unit_test_suite(int, char* [])
{
    boost::unit_test::test_suite* test = BOOST_TEST_SUITE("non-blocking read test");
    test->add(BOOST_TEST_CASE(&nonblocking_read_test));
    return test;
}