summaryrefslogtreecommitdiff
path: root/Util.cs
blob: 532064ebe2ad2a0390051d85b62db718e60171c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
namespace HyperBooru.Util;

public static class Extensions {
    public static readonly string[] MagnitudeOrders = new[] {
        "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"
    };

    public static string? NullIfEmpty(this string s) {
      s = s.Trim();
      return string.IsNullOrEmpty(s) ? null : s;
    }

    public static DateTime? TryParseDateTimeUtc(this string s) {
        bool success = DateTime.TryParse(s, out var dateTime);
        return success ? DateTime.SpecifyKind(dateTime, DateTimeKind.Utc) : null;
    }

    public static string ToBytesSI(this long x) {
        var exp = (int) Math.Log10(x);
        var suffix = MagnitudeOrders.ElementAtOrDefault(exp / 3 - 1);
        if(suffix is null)
            return x.ToString();
        double n = x / Math.Pow(10, exp / 3 * 3);
        return $"{Math.Round(n, 2 - (exp % 3))} {suffix}B";
    }

    public static string ToStringHumanReadable(this TimeSpan t) {
        if(t.TotalMilliseconds < 1000)
            return string.Format("{0:0}ms", t.TotalMilliseconds);
        if(t.TotalSeconds < 60)
            return string.Format("{0:0.00}s", t.TotalSeconds);
        if(t.TotalMinutes < 60)
            return string.Format("{0:0}m{0:0}s", t.TotalMinutes, t.Seconds);
        if(t.TotalHours < 24)
            return string.Format("{0:0}h{0:0}m", t.TotalHours, t.Minutes);
        return string.Format("{0:0.00}d", t.TotalDays);
    }

    public static int GetRoundedHashCode(this DateTime dt) {
        var t = dt.ToUniversalTime();
        return HashCode.Combine(t.Year, t.Month, t.Date, t.Hour, t.Minute, t.Second);
    }
}

public class LimitedConcurrencyTaskScheduler : TaskScheduler {
    public sealed override int MaximumConcurrencyLevel =>
        maxConcurrency;

    private int maxConcurrency;

    [ThreadStatic]
    private static bool threadIsProcessingItems;

    private readonly LinkedList<Task> tasks = new();

    private int delegatesQueuedOrRunning = 0;

    public LimitedConcurrencyTaskScheduler() {
        maxConcurrency = Environment.ProcessorCount;
    }

    public LimitedConcurrencyTaskScheduler(int maxConcurrency) {
        if(maxConcurrency < 1)
            throw new ArgumentOutOfRangeException("maxConcurrency must be greater than 0");
        this.maxConcurrency = (int) maxConcurrency;
    }

    protected sealed override void QueueTask(Task task) {
        lock(tasks) {
            tasks.AddLast(task);
            if(delegatesQueuedOrRunning < maxConcurrency) {
                delegatesQueuedOrRunning++;
                NotifyThreadPoolOfPendingWork();
            }
        }
    }

    private void NotifyThreadPoolOfPendingWork() {
        ThreadPool.UnsafeQueueUserWorkItem(_ => {
            threadIsProcessingItems = true;
            try {
                while(true) {
                    Task item;
                    lock(tasks) {
                        if(tasks.Count == 0) {
                            delegatesQueuedOrRunning--;
                            break;
                        } else {
                            item = tasks.First.Value;
                            tasks.RemoveFirst();
                        }
                    }
                    TryExecuteTask(item);
                }
            } finally {
                threadIsProcessingItems = false;
            }
        }, null);
    }

    protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) {
        if(!threadIsProcessingItems)
            return false;

        if(taskWasPreviouslyQueued)
            return TryDequeue(task) ? TryExecuteTask(task) : false;
        else
            return TryExecuteTask(task);
    }

    protected sealed override bool TryDequeue(Task task) {
        lock(tasks) {
            return tasks.Remove(task);
        }
    }

    protected sealed override IEnumerable<Task> GetScheduledTasks() {
        bool lockTaken = false;
        try {
            Monitor.TryEnter(tasks, ref lockTaken);
            if(lockTaken)
                return tasks;
            else
                throw new NotSupportedException();
        } finally {
            if(lockTaken)
                Monitor.Exit(tasks);
        }
    }
}