1 /*
2  * This file Copyright (C) 2010-2014 Mnemosyne LLC
3  *
4  * It may be used under the GNU GPL versions 2 or 3
5  * or any future license endorsed by Mnemosyne LLC.
6  *
7  */
8 
9 #include <string.h> /* memset() */
10 
11 #include "transmission.h"
12 #include "history.h"
13 #include "utils.h"
14 
tr_historyAdd(tr_recentHistory * h,time_t now,unsigned int n)15 void tr_historyAdd(tr_recentHistory* h, time_t now, unsigned int n)
16 {
17     if (h->slices[h->newest].date == now)
18     {
19         h->slices[h->newest].n += n;
20     }
21     else
22     {
23         if (++h->newest == TR_RECENT_HISTORY_PERIOD_SEC)
24         {
25             h->newest = 0;
26         }
27 
28         h->slices[h->newest].date = now;
29         h->slices[h->newest].n = n;
30     }
31 }
32 
tr_historyGet(tr_recentHistory const * h,time_t now,unsigned int sec)33 unsigned int tr_historyGet(tr_recentHistory const* h, time_t now, unsigned int sec)
34 {
35     unsigned int n = 0;
36     time_t const cutoff = (now != 0 ? now : tr_time()) - sec;
37     int i = h->newest;
38 
39     for (;;)
40     {
41         if (h->slices[i].date <= cutoff)
42         {
43             break;
44         }
45 
46         n += h->slices[i].n;
47 
48         if (--i == -1)
49         {
50             i = TR_RECENT_HISTORY_PERIOD_SEC - 1; /* circular history */
51         }
52 
53         if (i == h->newest)
54         {
55             break; /* we've come all the way around */
56         }
57     }
58 
59     return n;
60 }
61