Lastly, I have decided to create a new library for .NET core that handles (big) prime numbers. You know - testing, generating and other stuff that could be useful for playing with big numbers.
It is obvious that to accomplish this, I needed a service that should generate a bunch of random values. Easy task? Yep!
The only method I need is to generate random bytes that are placed in a buffer - our numbers could much more beyond int/long range, so I have decided to represent numbers as the byte array (like BigInteger it does).
Usage & Testing
Random provider is used to generate random big integer below a specified range, fe.
See snippet below:
Like a model programmer, I wrote some unit tests ran by xUnit:
Disclaimer: Tests are simple as possible to simplify the case.
I have ran my tests and… Testing has never ever finished. Or even failed. Just like an endless loop.
What went wrong
I have spent couple hours to find out the cause of this weird behavior (my tests % snippets are much more complicated).
Indeed, the problem was an endless loop… here:
It turned out, that xUnit runs tests in separate threads. What’s more, Random.NextBytes is not threadsafe, so… it started to fill bytes with 0 when more than one thread accessed it at the same time.