using System; using System.Text; using Cobilas.Collections; namespace Cobilas { /// Represents a list of switches. [Serializable] public struct Interrupter : IDisposable { private int currentIndex; private bool useASwitch; private bool disposable; private bool[] _switches; /// Returns the current switch index. public int CurrentIndex { get { WasDiscarded(); return currentIndex; } } ///This property allows the exchange of a single switch for multiple switches and vice versa. public bool UseASwitch { get { WasDiscarded(); return useASwitch; } set { WasDiscarded(); useASwitch = value; } } /// Gets or sets a switch when specifying an index. public bool this[int Index] { get { WasDiscarded(); return _switches[Index]; } set { WasDiscarded(); if (currentIndex != Index && useASwitch) { for (int I = 0; I < _switches.Length; I++) if (I != Index) _switches[I] = false; currentIndex = Index; } _switches[Index] = value; } } /// Only one switch specifying the index will be used, the others will remain at false value. /// How many switches. /// Allows you to use one switch at a time. public Interrupter(int Capacity, bool UseASwitch) { _switches = new bool[Capacity]; currentIndex = -1; useASwitch = UseASwitch; disposable = false; } /// Only one switch specifying the index will be used, the others will remain at false value. /// How many switches. public Interrupter(int Capacity) : this(Capacity, true) { } /// Returns a text representation of the object. public override string ToString() { WasDiscarded(); StringBuilder builder = new StringBuilder(); builder.AppendLine("Switches {"); for (int I = 0; I < _switches.Length; I++) builder.AppendLine($"\tswitch({I})[status:{_switches[I]}]"); builder.AppendLine("}"); return builder.ToString(); } /// Resource disposal. public void Dispose() { WasDiscarded(); disposable = true; useASwitch = default; currentIndex = default; ArrayManipulation.ClearArraySafe(ref _switches); } private void WasDiscarded() { if (disposable) throw new ObjectDisposedException("The object has already been discarded."); } } }