Skip to content

Add a diagnostic hint to input stream error#318

Open
swebb2066 wants to merge 1 commit into
boostorg:developfrom
swebb2066:develop
Open

Add a diagnostic hint to input stream error#318
swebb2066 wants to merge 1 commit into
boostorg:developfrom
swebb2066:develop

Conversation

@swebb2066

Copy link
Copy Markdown

This PR aims to save users some time when diagnosing an input_stream_error.

For example, a NaN value serialized as <PlanningCost>-nan(ind)</PlanningCost> results in an input_stream_error exception when the file is reloaded.

@gennaroprota

gennaroprota commented Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Thanks for this, and welcome. Adding the stream offset to input_stream_error is a genuinely useful idea; that error is otherwise very hard to diagnose. A few things need addressing before it can go in.

  • itoa is not part of standard C or C++. std::to_string is the direct replacement.
  • is.tellg() returns std::streampos, not int. Converting through std::streamoff gives you a proper integer offset without truncating large positions.
  • static char at_offset[64] is a single buffer shared across all threads and all calls, so two threads deserializing at once would corrupt each other's message. Building the text in a local std::string removes both the sharing and the manual buffer arithmetic (the fixed size and the &at_offset[10] offset).
  • tellg() returns -1 when the stream is already in a failed state, so it is worth guarding against reporting "offset -1".

Putting those together, the body could be something like:

template<class T>
void load(T & t)
{
    const std::streampos pos = is.tellg();
    if(is >> t)
        return;
    std::string msg("at offset ");
    msg += (std::streampos(-1) == pos)
        ? "<unknown>"
        : std::to_string(static_cast<std::streamoff>(pos));
    boost::serialization::throw_exception(
        archive_exception(
            archive_exception::input_stream_error,
            msg.c_str()
        )
    );
}

(msg stays alive across the throw_exception call, and archive_exception copies the text into its own buffer.) This needs #include <string> rather than <cstdlib>.

Two more things to consider. First, std::to_string is C++11; if C++03 support still matters here, a local buffer written with std::snprintf would be the portable equivalent. Second, the same input_stream_error is thrown from the binary and XML primitives as well, so if you want the offset reported consistently it would be worth applying the same treatment there (factoring the "position to message" helper so all three share it).

Thanks again for taking a look at this area.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants