source: trunk/libtransmission/history.c @ 11599

Last change on this file since 11599 was 11599, checked in by charles, 11 years ago

(trunk) Join the 21st century and use only 1 space at the end sentences. This commit is nearly as important as the semi-annual ones that remove trailing spaces from the ends of lines of code... :)

  • 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 11599 2010-12-27 19:18:17Z charles $
11 */
12
13#include <assert.h>
14
15#include "transmission.h"
16#include "history.h"
17#include "utils.h"
18
19struct history_slice
20{
21    unsigned int n;
22    time_t date;
23};
24
25struct tr_recentHistory
26{
27    int newest;
28    int sliceCount;
29    unsigned int precision;
30    struct history_slice * slices;
31};
32
33void
34tr_historyAdd( tr_recentHistory * h, time_t now, unsigned int n )
35{
36    if( h->slices[h->newest].date + (time_t)h->precision >= now )
37        h->slices[h->newest].n += n;
38    else {
39        if( ++h->newest == h->sliceCount ) h->newest = 0;
40        h->slices[h->newest].date = now;
41        h->slices[h->newest].n = n;
42    }
43}
44
45unsigned int
46tr_historyGet( const tr_recentHistory * h, time_t now, unsigned int sec )
47{
48    unsigned int n = 0;
49    const time_t cutoff = (now?now:tr_time()) - sec;
50    int i = h->newest;
51
52    for( ;; )
53    {
54        if( h->slices[i].date <= cutoff )
55            break;
56
57        n += h->slices[i].n;
58
59        if( --i == -1 ) i = h->sliceCount - 1; /* circular history */
60        if( i == h->newest ) break; /* we've come all the way around */
61    }
62
63    return n;
64}
65
66tr_recentHistory *
67tr_historyNew( unsigned int seconds, unsigned int precision )
68{
69    tr_recentHistory * h;
70
71    assert( precision <= seconds );
72
73    h = tr_new0( tr_recentHistory, 1 );
74    h->precision = precision;
75    h->sliceCount = seconds / precision;
76    h->slices = tr_new0( struct history_slice, h->sliceCount );
77
78    return h;
79}
80
81void
82tr_historyFree( tr_recentHistory * h )
83{
84    tr_free( h->slices );
85    tr_free( h );
86}
Note: See TracBrowser for help on using the repository browser.