            let write_res = stream.write(&buffer[0..bytes_read]);
            if write_res.is_ok() {
                let bytes_written = write_res.unwrap();
                assert!(bytes_written == bytes_read);

                if bytes_read < BUFFER_SIZE {
                    break;
                }
                
                // buffer is extended each time read_to_end() is called, so we need this.
                // In theory, it should be very cheap, as it doesn't de-allocate the memory...
                buffer.clear();