Skip to content

writer: keep the writer usable after an UnequalLengths error - #439

Open
patrick-immometrica wants to merge 1 commit into
BurntSushi:masterfrom
patrick-immometrica:fix-writer-unequal-lengths
Open

patrick-immometrica wants to merge 1 commit into
BurntSushi:masterfrom
patrick-immometrica:fix-writer-unequal-lengths

Conversation

@patrick-immometrica

Copy link
Copy Markdown

With the default flexible(false), one record with the wrong field count breaks every write after it:

let mut wtr = Writer::from_writer(vec![]);
wtr.write_record(&["a", "b"])?;
assert!(wtr.write_record(&["x", "y", "z"]).is_err());
wtr.write_record(&["c", "d"])?; // UnequalLengths { expected_len: 2, len: 5 }

The check runs before the terminator is written and fields_written is never reset, so the bad record's fields stay in the buffer, the next record is appended to the same line and the count only grows from there.

Rolling the record back isn't possible since write_field may already have flushed part of it, so this writes the terminator and resets the counter first, then returns the error. The bad record still ends up in the output (as before), but it is on its own line and later records are fine.

Added a test covering both write_record and write_byte_record.

With `flexible(false)`, a record with the wrong number of fields returned
`UnequalLengths` before the terminator was written and without resetting
the field counter. The record's fields were already in the buffer, so the
next record got glued onto it and every following write failed too, since
the counter kept growing.

Now the terminator is written and the counter reset before the error is
returned, so the writer stays usable.
@patrick-immometrica
patrick-immometrica marked this pull request as ready for review November 14, 2026 11:11
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.

1 participant