source: trunk/libtransmission/history.c @ 11280

Last change on this file since 11280 was 11280, checked in by charles, 12 years ago

(trunk) fix svn properties on several files. Thanks ot Elbandi for suggesting this

  • Property svn:keywords set to Date Rev Author Id
File size: 1.8 KB
Line 
1/*
2 * This file Copyright (C) 2010 Mnemosyne LLC
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id: history.c 11280 2010-10-01 13:33:39Z charles $
11 */
12
13#include "transmission.h"
14#include "history.h"
15#include "utils.h"
16
17struct history_slice
18{
19    unsigned int n;
20    uint64_t date;
21};
22
23struct tr_recentHistory
24{
25    int newest;
26    int sliceCount;
27    unsigned int precision_msec;
28    struct history_slice * slices;
29};
30
31void
32tr_historyAdd( tr_recentHistory * h, uint64_t now, unsigned int n )
33{
34    if( h->slices[h->newest].date + h->precision_msec >= now )
35        h->slices[h->newest].n += n;
36    else {
37        if( ++h->newest == h->sliceCount ) h->newest = 0;
38        h->slices[h->newest].date = now;
39        h->slices[h->newest].n = n;
40    }
41}
42
43unsigned int
44tr_historyGet( const tr_recentHistory * h, uint64_t now, unsigned int msec )
45{
46    unsigned int n = 0;
47    const uint64_t cutoff = (now?now:tr_time_msec()) - msec;
48    int i = h->newest;
49
50    for( ;; )
51    {
52        if( h->slices[i].date <= cutoff )
53            break;
54
55        n += h->slices[i].n;
56
57        if( --i == -1 ) i = h->sliceCount - 1; /* circular history */
58        if( i == h->newest ) break; /* we've come all the way around */
59    }
60
61    return n;
62}
63
64tr_recentHistory *
65tr_historyNew( unsigned int seconds, unsigned int bins_per_second )
66{
67    tr_recentHistory * h;
68
69    h = tr_new0( tr_recentHistory, 1 );
70    h->precision_msec = 1000 / bins_per_second;
71    h->sliceCount = (int)(seconds * bins_per_second);
72    h->slices = tr_new0( struct history_slice, h->sliceCount );
73
74    return h;
75}
76
77void
78tr_historyFree( tr_recentHistory * h )
79{
80    tr_free( h->slices );
81    tr_free( h );
82}
Note: See TracBrowser for help on using the repository browser.