How to detect a error with a StreamPeer?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Anm

For instance, how do you detect the end of a stream? There isn’t even a has_next() sort of method. The following test merrily returns a valid byte value (0) after the end of the stream:

func test_end_of_buffer():
    var stream = StreamPeerBuffer.new()
    stream.data_array = PoolByteArray([1,2,3])
    
    asserts.is_equal(1, stream.get_u8(), "First u8 value")
    asserts.is_equal(2, stream.get_u8(), "Second u8 value")
    asserts.is_equal(3, stream.get_u8(), "Third u8 value")
    # End of buffer

    # What? Why? 0 is a valid value!
    asserts.is_equal(0, stream.get_u8(), "EOF u8 value") 
:bust_in_silhouette: Reply From: Anm

Check for EOF by checking available bytes before reading the data:

func test_end_of_buffer():
    var stream = StreamPeerBuffer.new()
    stream.data_array = PoolByteArray([1,2,3])

    var bytes = stream.get_available_bytes()
    asserts.is_equal(3, stream.get_available_bytes())   

    asserts.is_equal(1, stream.get_u8())
    asserts.is_equal(2, stream.get_u8())
    asserts.is_equal(3, stream.get_u8())
    # End of buffer

    if (bytes > 3):
        # This will never run
        asserts.is_equal(-1, stream.get_u8(), "value after EOF")

Not quite a useful as an error code, but solves 99% of the cases.