/ ProjectPlugins / CodexClient / TransferSpeeds.cs
TransferSpeeds.cs
 1  using Utils;
 2  
 3  namespace CodexClient
 4  {
 5      public interface ITransferSpeeds
 6      {
 7          BytesPerSecond? GetUploadSpeed();
 8          BytesPerSecond? GetDownloadSpeed();
 9          ITransferSpeeds Combine(ITransferSpeeds? other);
10      }
11  
12      public class TransferSpeeds : ITransferSpeeds
13      {
14          private readonly List<BytesPerSecond> uploads = new List<BytesPerSecond>();
15          private readonly List<BytesPerSecond> downloads = new List<BytesPerSecond>();
16  
17          public void AddUploadSample(ByteSize bytes, TimeSpan duration)
18          {
19              uploads.Add(Convert(bytes, duration));
20          }
21  
22          public void AddDownloadSample(ByteSize bytes, TimeSpan duration)
23          {
24              downloads.Add(Convert(bytes, duration));
25          }
26  
27          public BytesPerSecond? GetUploadSpeed()
28          {
29              if (!uploads.Any()) return null;
30              return uploads.Average();
31          }
32  
33          public BytesPerSecond? GetDownloadSpeed()
34          {
35              if (!downloads.Any()) return null;
36              return downloads.Average();
37          }
38  
39          public ITransferSpeeds Combine(ITransferSpeeds? other)
40          {
41              if (other == null) return this;
42              var o = (TransferSpeeds)other;
43              var result = new TransferSpeeds();
44              result.uploads.AddRange(uploads);
45              result.uploads.AddRange(o.uploads);
46              result.downloads.AddRange(downloads);
47              result.downloads.AddRange(o.downloads);
48              return result;
49          }
50  
51          private static BytesPerSecond Convert(ByteSize size, TimeSpan duration)
52          {
53              double bytes = size.SizeInBytes;
54              double seconds = duration.TotalSeconds;
55  
56              return new BytesPerSecond(System.Convert.ToInt64(Math.Round(bytes / seconds)));
57          }
58      }
59  
60      public static class ListExtensions
61      {
62          public static BytesPerSecond Average(this List<BytesPerSecond> list)
63          {
64              double sum = list.Sum(i => i.SizeInBytes);
65              double num = list.Count;
66  
67              return new BytesPerSecond(Convert.ToInt64(Math.Round(sum / num)));
68          }
69  
70          public static BytesPerSecond? OptionalAverage(this List<BytesPerSecond?>? list)
71          {
72              if (list == null || !list.Any() || !list.Any(i => i != null)) return null;
73              var values = list.Where(i => i != null).Cast<BytesPerSecond>().ToArray();
74              double sum = values.Sum(i => i.SizeInBytes);
75              double num = values.Length;
76  
77              return new BytesPerSecond(Convert.ToInt64(Math.Round(sum / num)));
78          }
79      }
80  }