NetPeerCollection.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA_8_1
  2. using System;
  3. using System.Collections.Generic;
  4. namespace FlyingWormConsole3.LiteNetLib
  5. {
  6. internal sealed class NetPeerCollection
  7. {
  8. private readonly Dictionary<NetEndPoint, NetPeer> _peersDict;
  9. private readonly NetPeer[] _peersArray;
  10. private int _count;
  11. public int Count
  12. {
  13. get { return _count; }
  14. }
  15. public NetPeer this[int index]
  16. {
  17. get { return _peersArray[index]; }
  18. }
  19. public NetPeerCollection(int maxPeers)
  20. {
  21. _peersArray = new NetPeer[maxPeers];
  22. _peersDict = new Dictionary<NetEndPoint, NetPeer>();
  23. }
  24. public bool TryGetValue(NetEndPoint endPoint, out NetPeer peer)
  25. {
  26. return _peersDict.TryGetValue(endPoint, out peer);
  27. }
  28. public void Clear()
  29. {
  30. Array.Clear(_peersArray, 0, _count);
  31. _peersDict.Clear();
  32. _count = 0;
  33. }
  34. public void Add(NetEndPoint endPoint, NetPeer peer)
  35. {
  36. _peersArray[_count] = peer;
  37. _peersDict.Add(endPoint, peer);
  38. _count++;
  39. }
  40. public bool ContainsAddress(NetEndPoint endPoint)
  41. {
  42. return _peersDict.ContainsKey(endPoint);
  43. }
  44. public NetPeer[] ToArray()
  45. {
  46. NetPeer[] result = new NetPeer[_count];
  47. Array.Copy(_peersArray, 0, result, 0, _count);
  48. return result;
  49. }
  50. public void RemoveAt(int idx)
  51. {
  52. _peersDict.Remove(_peersArray[idx].EndPoint);
  53. _peersArray[idx] = _peersArray[_count - 1];
  54. _peersArray[_count - 1] = null;
  55. _count--;
  56. }
  57. public void Remove(NetEndPoint endPoint)
  58. {
  59. for (int i = 0; i < _count; i++)
  60. {
  61. if (_peersArray[i].EndPoint.Equals(endPoint))
  62. {
  63. RemoveAt(i);
  64. break;
  65. }
  66. }
  67. }
  68. }
  69. }
  70. #endif