FR: Return empty ValueTree if input stream data corrupted

Currently, if you attempt to load a juce::ValueTree from some binary data using juce::ValueTree::readFromStream(), an assertion will be hit if the given data is corrupt. However, continuing through these assertions until the full stream has been read results in a ‘valid’ tree.

Unless there’s another way around this, it seems there’s no way to check if the data was corrupt when reading corrupt data without a debugger. It would be much nicer if readFromStream simply returned an empty tree if it detects corrupt data.


Here’s a quick example:

    // Valid data
    {
        juce::uint8 data[] = { 0x4d, 0x79, 0x54, 0x72, 0x65, 0x65, 0x00, 0x01,
                               0x01, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x00, 0x01,
                               0x05, 0x01, 0x7b, 0x00, 0x00, 0x00, 0x00, 0x00,
                               0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        juce::MemoryInputStream mis { data, 32, false };
        const auto tree = juce::ValueTree::readFromStream (mis);

        std::cout << "Valid data:\n" << tree.toXmlString() << std::endl;
    }

    // Invalid data
    {
        juce::uint8 data[] = { 0x4d, /*0x79,*/ 0x54, 0x72, 0x65, /*0x65,*/ 0x00, 0x01,
                               /*0x01,*/ 0x56, 0x61, 0x6c, /*0x75,*/ 0x65, 0x00, 0x01,
                               0x05, 0x01, /*0x7b,*/ 0x00, 0x00, /*0x00,*/ 0x00, 0x00,
                               0x00, /*0x00,*/ 0x00, 0x00, 0x00, 0x00, /*0x00,*/ 0x00 };
        juce::MemoryInputStream mis { data, 32, false };
        const auto tree = juce::ValueTree::readFromStream (mis);

        std::cout << "Invalid data:\n" << tree.toXmlString() << std::endl;
    }

Running the above with a debugger attached will break at the following assertion:

Simplest solution is possibly just to return {} on the line after that assertion?

2 Likes