/* WinUSBNet library * (C) 2010 Thomas Bleeker (www.madwizard.org) * * Licensed under the MIT license, see license.txt or: * http://www.opensource.org/licenses/mit-license.php */ using System; using System.Collections; using System.Collections.Generic; namespace MadWizard.WinUSBNet { /// /// Collection of UsbPipe objects /// public class USBPipeCollection : IEnumerable { private readonly Dictionary _pipes; internal USBPipeCollection(USBPipe[] pipes) { _pipes = new Dictionary(pipes.Length); foreach (USBPipe pipe in pipes) { if (_pipes.ContainsKey(pipe.Address)) { throw new USBException("Duplicate pipe address in endpoint."); } _pipes[pipe.Address] = pipe; } } /// /// Returns the pipe from the collection with the given pipe address /// /// Address of the pipe to return /// The pipe with the given pipe address /// Thrown if no pipe with the specified address /// is available in the collection. public USBPipe this[byte pipeAddress] { get { if (!_pipes.TryGetValue(pipeAddress, out USBPipe pipe)) { throw new IndexOutOfRangeException(); } return pipe; } } private class UsbPipeEnumerator : IEnumerator { private int _index; private readonly USBPipe[] _pipes; public UsbPipeEnumerator(USBPipe[] pipes) { _pipes = pipes; _index = -1; } public void Dispose() { // Empty } private USBPipe GetCurrent() { try { return _pipes[_index]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } public USBPipe Current { get { return GetCurrent(); } } object IEnumerator.Current { get { return GetCurrent(); } } public bool MoveNext() { _index++; return _index < _pipes.Length; } public void Reset() { _index = -1; } } private USBPipe[] GetPipeList() { var values = _pipes.Values; USBPipe[] pipeList = new USBPipe[values.Count]; values.CopyTo(pipeList, 0); return pipeList; } /// /// Returns a typed enumerator that iterates through a collection. /// /// The enumerator object that can be used to iterate through the collection. public IEnumerator GetEnumerator() { return new UsbPipeEnumerator(GetPipeList()); } /// /// Returns an enumerator that iterates through a collection. /// /// An IEnumerator object that can be used to iterate through the collection. IEnumerator IEnumerable.GetEnumerator() { return new UsbPipeEnumerator(GetPipeList()); } } }