Client LuaCsForBarotrauma
LeakyBucket.cs
1 #nullable enable
2 
3 using System;
4 using System.Collections.Generic;
5 
6 namespace Barotrauma
7 {
8  internal class LeakyBucket
9  {
10  private readonly Queue<Action> queue;
11  private readonly int capacity;
12  private readonly float cooldownInSeconds;
13  private float timer;
14 
15  public LeakyBucket(float cooldownInSeconds, int capacity)
16  {
17  this.cooldownInSeconds = cooldownInSeconds;
18  this.capacity = capacity;
19  queue = new Queue<Action>(capacity);
20  }
21 
22  public void Update(float deltaTime)
23  {
24  if (timer > 0f)
25  {
26  timer -= deltaTime;
27  return;
28  }
29 
30  if (queue.Count is 0) { return; }
31 
32  TryDequeue();
33  }
34 
35  private void TryDequeue()
36  {
37  timer = cooldownInSeconds;
38  if (queue.TryDequeue(out var action))
39  {
40  action.Invoke();
41  }
42  }
43 
44  public bool TryEnqueue(Action item)
45  {
46  if (queue.Count >= capacity) { return false; }
47  queue.Enqueue(item);
48  return true;
49  }
50  }
51 }