Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Threading.Tasks;
- namespace uuid_bad_code
- {
- /// <summary>
- /// Program
- /// </summary>
- class Program
- {
- /// <summary>
- /// Main function
- /// </summary>
- static void Main()
- {
- IUuidGenerator generator = new UuidGenerator(new List<char>
- {
- '0',
- '1',
- '2',
- '3',
- '4',
- '5',
- '6',
- '7',
- '8',
- '9',
- 'a',
- 'b',
- 'c',
- 'd',
- 'e',
- 'f',
- '-'
- }, new Random(Guid.NewGuid().GetHashCode())); // Not sure what "Guid.NewGuid().GetHashCode()" does, found it on StackOverflow
- var uuid = generator.Generate();
- Console.WriteLine($"The uuid is: {uuid}");
- Console.ReadKey();
- }
- }
- /// <summary>
- /// An interface for UUID generators
- /// </summary>
- public interface IUuidGenerator
- {
- /// <summary>
- /// Generates
- /// </summary>
- /// <returns>A generated string</returns>
- string Generate();
- }
- /// <summary>
- /// A UUID generator
- /// </summary>
- public class UuidGenerator: IUuidGenerator
- {
- /// <summary>
- /// The number of legal chars including hyphens and numbers
- /// </summary>
- private const int NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell = 17;
- /// <summary>
- /// Legal chars
- /// </summary>
- private readonly IList<char> _legalChars;
- /// <summary>
- /// The <see cref="Random"/> class object
- /// </summary>
- private readonly Random _random;
- /// <summary>
- /// A lock for <see cref="_random"/> access
- /// </summary>
- private readonly object _randomLock;
- /// <summary>
- /// The UUID generator constructor
- /// </summary>
- /// <param name="legalChars">Legal chars</param>
- /// <param name="random">The <see cref="Random"/> class object</param>
- public UuidGenerator(IList<char> legalChars, Random random)
- {
- _legalChars = legalChars ?? throw new ArgumentNullException(nameof(legalChars));
- _random = random ?? throw new ArgumentNullException(nameof(random));
- _randomLock = new Object();
- }
- /// <summary>
- /// Generates
- /// </summary>
- /// <returns>A generated string</returns>
- public string Generate()
- {
- var time = Stopwatch.StartNew();
- // It should be a 128-bit number displayed in five groups separated by hyphens in the form 8-4-4-4-12
- // 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12 = 36
- // 8 13 18 23
- const int numberOfCharsInLegalUuidStringIncludingHyphensAndIncludingNumbersAsWell = 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12;
- ConcurrentDictionary<int, char> uuid = new ConcurrentDictionary<int, char>();
- int iterations = 0;
- bool uuidLegal = false;
- while (!uuidLegal)
- {
- iterations++;
- List<int> indicesWhereHyphensShouldBe = new List<int>
- {
- 8, 13, 18, 23
- };
- // We run this in parallel because it's faster
- Parallel.For(0, numberOfCharsInLegalUuidStringIncludingHyphensAndIncludingNumbersAsWell, index =>
- {
- // Need to lock before accessing the random class per MSDN
- // https://docs.microsoft.com/en-us/dotnet/api/system.random?redirectedfrom=MSDN&view=netcore-3.1#ThreadSafety
- lock (_randomLock)
- {
- if (_legalChars.ToList().Count != NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell)
- {
- throw new InvalidOperationException($"Can't generate random number because the legal chars list doesn't contain exactly {NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell} characters!");
- }
- int charIndex = _random.Next(_legalChars.ToList().Count);
- uuid[index] = _legalChars.ToList()[charIndex];
- }
- });
- var uuidLegalLock = new Object();
- var isUuidLegal = true;
- Parallel.For(0, uuid.Count, i =>
- {
- lock (uuidLegalLock)
- {
- isUuidLegal = isUuidLegal &&
- (indicesWhereHyphensShouldBe.ToList().Contains(i) && uuid[i] == '-' ||
- !indicesWhereHyphensShouldBe.ToList().Contains(i) &&
- uuid[i] != '-' &&
- _legalChars.ToList().Contains(uuid[i]));
- }
- });
- uuidLegal = isUuidLegal;
- }
- time.Stop();
- Console.WriteLine($"Finished generating UUID after {time.Elapsed.TotalSeconds} seconds ({iterations} iterations)");
- return new string(uuid.Values.ToArray());
- }
- }
- }
Add Comment
Please, Sign In to add comment