Search code examples
c++boostasio

Asio sync-read random-access with exceptions, how many bytes were read?


How can we know how many bytes were read when calling a synchronous read operation on a random-access device and it throws an exception, for example random_access_file ?

Is this not supported, and to know how many bytes were read, one is supposed to take the boost::system::error_code ec overload?

error_code ec;
size_t s = a.read_some_at(offset, buffers, ec);
offset += s; // need to be done before unwinding
if (ec) throw system_error(ec);
return s;

Solution

  • Short answer: Yes. Take the ec overload. This has been the case for partial-success operations in Asio.

    Slightly longer (irrelevant) answer: when using e.g. c++20 coroutines you can make the error-code and byte-count be returned as a tuple, which you might find more convenient:

    auto [ec, s] = a.async_read_some_at(offset, buffers, asio::as_tuple(asio::use_awaitable)));
    

    Pet peeve: as_tuple doesn't at current (last checked 1.80.0) appear to work well with asio::use_future :(