jsakamoto / ipaddressrange

.NET Class Library for range of IP address, both IPv4 and IPv6.
Mozilla Public License 2.0
368 stars 71 forks source link

.Count() is dangerous #17

Closed defcon84 closed 9 years ago

defcon84 commented 9 years ago

Not really an IPAddressRange issue, but maybe an IEnumerable issue.

But if you use IPAddressRange.Count() on a large list of IPs, it will perform bad and take minutes.

for example: IPAddressRange.Parse("0.0.0.0/1").Count()

or even worse: IPAddressRange.Parse("0::0/0").Count()

defcon84 commented 9 years ago

maybe something like:

public double Count()
{
    byte[] byteBegin = this.Begin.GetAddressBytes();
    byte[] byteEnd = this.End.GetAddressBytes();

    double sum = 1;
    for (int i = byteBegin.Length - 1;i >= 0;i--) {
        if (byteEnd[i] - byteBegin[i] == 0)
            continue;

        sum += (byteEnd[i] - byteBegin[i]) * Math.Pow(2D, (double)((byteBegin.Length - 1) - i) * 8);
    }

    return sum;
}
jsakamoto commented 9 years ago

Hi, @defcon84,
Thank you for your issue.
But I would like to do not any actions about this issue. This is by design.

Dangerous LINQ operations are not only Count() method. ToArray(), ToList(), and also simple foreach enumeration are dangerous too.
Many lazy evaluation systems have this problem, not only the IEnumarable interface of this library.

Of course, we can avoid this issue by implement custom Count() method such as your example code.

But, I feel it is over spec about implement custom Count() method on this library.

This is my answer.
Would you tell me your opinion, @defcon84 or anybody else?

defcon84 commented 9 years ago

Yes, as i said in my first message, i know this is not the issue of this library. And maybe it's best not to implement it. I just wanted to warn people and give them an alternative for it.

Thank you for this library!

jsakamoto commented 9 years ago

Hi @defcon84 , thank you for your reply.

I just wanted to warn people and give them an alternative for it.

Oh, sorry, it's my mistake of reading your post. Thank you for your useful post :smile:

defcon84 commented 9 years ago

no problem :)

and thank you!