4
using System.Collections.Generic;
5
using System.Text.RegularExpressions;
10
namespace Transmission {
14
public static int ParseSpeed(string speed) {
15
Regex regex = new Regex(
16
@"^(\d+)\s*(b|[km]i?b?)$",
17
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace
19
Match match = regex.Match(speed);
22
int number = int.Parse(match.Groups[1].Value);
23
string unit = match.Groups[2].Value.ToLower();
26
if (unit == "" || unit[0] == 'k') scale = 1;
27
else if (unit[0] == 'm') scale = 1024;
29
return number * scale;
32
throw new ArgumentException("Invalid speed string");
36
public static string FormatAmount(float amount, string baseFormat, float[] scales, string[] formats) {
37
if (scales.Length != formats.Length)
38
throw new ArgumentException("'scales' and 'formats' arguments must have equal length");
40
// The typical scales count is three to five, so don't use binary search,
41
// but just plain reverse loop.
42
for (int i = scales.Length-1; i >= 0; --i) {
43
if (amount >= scales[i])
44
return string.Format(formats[i], amount / scales[i]);
47
return string.Format(baseFormat, amount);
50
// Format speed in KiB/sec into human-readable representation.
51
public static string FormatSpeed(int speed_kbytes_sec) {
52
return FormatAmount(speed_kbytes_sec, "{0} KiB/sec",
53
new float[] { 1024, 1024*1024},
54
new string[] {"{0:#.#} MiB/sec", "{0:#.#} GiB/sec"}
58
// Format size in bytes into human-readable representation.
59
public static string FormatSize(ulong size_bytes) {
60
return FormatAmount(size_bytes, "{0} B",
61
new float[] { 1024, 1024*1024, 1024*1024*1024},
62
new string[] {"{0:#.#} KiB", "{0:#.#} MiB", "{0:#.##} GiB"}
66
public readonly static IEnumerable<PredefinedSpeed> PredefinedSpeedItems = new List<PredefinedSpeed>() {
67
new PredefinedSpeed( 10, "10 KiB/sec", ""),
68
new PredefinedSpeed( 20, "20 KiB/sec", ""),
69
new PredefinedSpeed( 50, "50 KiB/sec", ""),
70
new PredefinedSpeed( 100, "100 KiB/sec", ""),
71
new PredefinedSpeed( 200, "200 KiB/sec", ""),
72
new PredefinedSpeed( 500, "500 KiB/sec", ""),
73
new PredefinedSpeed( 1 * 1024, "1 MiB/sec", ""),
74
new PredefinedSpeed( 2 * 1024, "2 MiB/sec", ""),
75
new PredefinedSpeed( 5 * 1024, "5 MiB/sec", ""),
76
new PredefinedSpeed( 10 * 1024, "10 MiB/sec", ""),
77
new PredefinedSpeed( 20 * 1024, "20 MiB/sec", ""),
78
new PredefinedSpeed( 50 * 1024, "50 MiB/sec", ""),
79
new PredefinedSpeed(100 * 1024, "100 MiB/sec", ""),
84
public class PredefinedSpeed: Item {
85
private string _name, _desc;
88
public PredefinedSpeed(int value, string name, string desc) {
94
public override string Name {
98
public override string Description {
102
public override string Icon {
103
get { return "top"; }
107
get { return _value; }