source: trunk/libtransmission/bitset.c @ 12003

Last change on this file since 12003 was 12003, checked in by jordan, 11 years ago

(trunk libT) code cleanup: moving bitset functions to their own .c file.

  • Property svn:keywords set to Date Rev Author Id
File size: 2.3 KB
Line 
1/*
2 * This file Copyright (C) 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: bitset.c 12003 2011-02-21 01:40:19Z jordan $
11 */
12
13#include "transmission.h"
14#include "bitset.h"
15
16void
17tr_bitsetConstructor( tr_bitset * b, size_t size )
18{
19    tr_bitfieldConstruct( &b->bitfield, size );
20}
21
22void
23tr_bitsetDestructor( tr_bitset * b )
24{
25    tr_bitfieldDestruct( &b->bitfield );
26}
27
28void
29tr_bitsetReserve( tr_bitset * b, size_t size )
30{
31    if( b->bitfield.bitCount < size )
32    {
33        tr_bitfield * tmp = tr_bitfieldDup( &b->bitfield );
34
35        tr_bitfieldDestruct( &b->bitfield );
36        tr_bitfieldConstruct( &b->bitfield, size );
37
38        if( ( tmp->bits != NULL ) && ( tmp->byteCount > 0 ) )
39            memcpy( b->bitfield.bits, tmp->bits, tmp->byteCount );
40
41        tr_bitfieldFree( tmp );
42    }
43}
44
45tr_bool
46tr_bitsetHas( const tr_bitset * b, const size_t nth )
47{
48    if( b->haveAll ) return TRUE;
49    if( b->haveNone ) return FALSE;
50    if( nth >= b->bitfield.bitCount ) return FALSE;
51    return tr_bitfieldHas( &b->bitfield, nth );
52}
53
54void
55tr_bitsetOr( tr_bitfield * a, const tr_bitset * b )
56{
57    if( b->haveAll )
58        tr_bitfieldAddRange( a, 0, a->bitCount );
59    else if( !b->haveNone )
60        tr_bitfieldOr( a, &b->bitfield );
61}
62
63/* set 'a' to all the flags that were in 'a' but not 'b' */
64void
65tr_bitsetDifference( tr_bitfield * a, const tr_bitset * b )
66{
67    if( b->haveAll )
68        tr_bitfieldClear( a );
69    else if( !b->haveNone )
70        tr_bitfieldDifference( a, &b->bitfield );
71}
72
73double
74tr_bitsetPercent( const tr_bitset * b )
75{
76    if( b->haveAll ) return 1.0;
77    if( b->haveNone ) return 0.0;
78    if( b->bitfield.bitCount == 0 ) return 0.0;
79    return tr_bitfieldCountTrueBits( &b->bitfield ) / (double)b->bitfield.bitCount;
80}
81
82void
83tr_bitsetSetHaveAll( tr_bitset * b )
84{
85    b->haveAll = 1;
86    b->haveNone = 0;
87}
88
89void
90tr_bitsetSetHaveNone( tr_bitset * b )
91{
92    b->haveAll = 0;
93    b->haveNone = 1;
94}
95
96int
97tr_bitsetAdd( tr_bitset * b, size_t i )
98{
99    int ret = 0;
100    if( !b->haveAll ) {
101        b->haveNone = 0;
102        tr_bitsetReserve( b, i+1 );
103        ret = tr_bitfieldAdd( &b->bitfield, i );
104    }
105    return ret;
106}
Note: See TracBrowser for help on using the repository browser.