Skip to content

Fix File.Stream Enumerable.count for files without trailing newline - #15147

Merged
josevalim merged 1 commit into
elixir-lang:mainfrom
pnezis:fix/file-stream-count-without-trailing-newline
Mar 7, 2026
Merged

Fix File.Stream Enumerable.count for files without trailing newline#15147
josevalim merged 1 commit into
elixir-lang:mainfrom
pnezis:fix/file-stream-count-without-trailing-newline

Conversation

@pnezis

@pnezis pnezis commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

The optimized count implementation was counting newline characters instead of actual lines, returning incorrect results for files that don't end with a newline (which is common for source code files).

For example, a file with content "line1\nline2\nline3" (3 lines) was returning 2 instead of 3.

The fix tracks the last byte read and adds 1 at EOF if the file has content but doesn't end with a newline.

You can reproduce it with:

iex> File.write!("/tmp/test.txt", "foo")
iex> stream = File.stream!("/tmp/test.txt")
iex> Enum.count(stream)
0

The optimized count implementation was counting newline characters
instead of actual lines, returning incorrect results for files that
don't end with a newline (which is common for source code files).

For example, a file with content "line1\nline2\nline3" (3 lines)
was returning 2 instead of 3.

The fix tracks the last byte read and adds 1 at EOF if the file
has content but doesn't end with a newline.
@josevalim
josevalim merged commit bbe7001 into elixir-lang:main Mar 7, 2026
15 checks passed
@josevalim

Copy link
Copy Markdown
Member

💚 💙 💜 💛 ❤️

@pnezis
pnezis deleted the fix/file-stream-count-without-trailing-newline branch March 11, 2026 10:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants