using System; using System.Linq; using System.Collections.Generic; namespace ServerEngine { public sealed class IDManager { private readonly object objLock = new object(); private readonly Stack freeValues; /// /// Initializes a new instance of the class. /// /// /// The smallest value that the ID's could take /// /// /// The highest possible ID /// public IDManager(int lowestPossible, int highestPossible) { lock (objLock) { // fail check lowestPossible = lowestPossible <= 0 ? 1 : lowestPossible; highestPossible = highestPossible > 1000000 ? 1000000 : highestPossible; if (lowestPossible >= highestPossible) { throw new IndexOutOfRangeException( "Lowest value must be at least 1 smaller than highest value"); } // create the freeID's stack var freeIDs = new List(); for (var i = highestPossible; i >= lowestPossible; i--) { freeIDs.Add(i); } freeValues = new Stack(freeIDs); } } /// /// This returns a currently unused ID. /// public int RequestID() { lock (objLock) { if (freeValues.Count != 0) { return freeValues.Pop(); } throw new IndexOutOfRangeException("No more free IDs"); } } /// /// This frees a used ID. /// public void FreeID(int toFree) { lock (objLock) { freeValues.Push(toFree); } } /// /// Try to register an ID /// public bool ClaimID(int toClaim) { return freeValues.Contains(toClaim) ? freeValues.ToList().Remove(toClaim) : false; } } }