Skip to content

LINQ Append and Prepend in Count speed optimization can overflow #123820

@vcsjones

Description

@vcsjones

The Prepend and Append LINQ implementation contains a speed optimization for GetCount that can overflow. There are two speed optimizations, AppendPrepend1Iterator and AppendPrependN and both appear to have overflows in their GetCount implementation, and each implementation can overflow differently depending on if the source implementation has a GetCount speed optimization.

To demonstrate a few of the issues.

The following will print -2147483648, and overflows in AppendPrepend1Iterator

var source = Enumerable.Repeat(0, int.MaxValue);
var appended = source.Append(1);
Console.WriteLine(appended.Count());

The following will print -2147483647 and overflows in AppendPrependN:

var source = Enumerable.Repeat(0, int.MaxValue);
var appended = source.Append(1).Prepend(2);
Console.WriteLine(appended.Count());

Generally, GetCount throws an OverflowException when the count cannot be represented as a 32-bit integer.

For example, with Concat, this will throw OverflowException

var source = Enumerable.Repeat(0, int.MaxValue);
var appended = source.Concat([1]);
Console.WriteLine(appended.Count());

It seems like the Append and Prepend speed optimizations should used checked arithmetic in their GetCount implementations.

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions