Ignore:
Timestamp:
Mar 5, 2007, 11:03:38 PM (15 years ago)
Author:
joshe
Message:

Do bounds checking on bitfields.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/libtransmission/utils.h

    r1444 r1534  
    102102}
    103103
     104struct tr_bitfield_s
     105{
     106    uint8_t * bits;
     107    int       len;
     108};
     109
     110/* note that the argument is how many bits are needed, not bytes */
     111static inline tr_bitfield_t * tr_bitfieldNew( int bitcount )
     112{
     113    tr_bitfield_t * ret;
     114
     115    ret = calloc( 1, sizeof *ret );
     116    if( NULL == ret )
     117    {
     118        return NULL;
     119    }
     120    ret->len = ( bitcount + 7 ) / 8;
     121    ret->bits = calloc( ret->len, 1 );
     122    if( NULL == ret->bits )
     123    {
     124        free( ret );
     125        return NULL;
     126    }
     127
     128    return ret;
     129}
     130
     131static inline void tr_bitfieldFree( tr_bitfield_t * bitfield )
     132{
     133    if( bitfield )
     134    {
     135        free( bitfield->bits );
     136        free( bitfield );
     137    }
     138}
     139
     140static inline void tr_bitfieldClear( tr_bitfield_t * bitfield )
     141{
     142    memset( bitfield->bits, 0, bitfield->len );
     143}
     144
    104145/***********************************************************************
    105146 * tr_bitfieldHas
    106147 **********************************************************************/
    107 static inline int tr_bitfieldHas( uint8_t * bitfield, int piece )
    108 {
    109     return ( bitfield[ piece / 8 ] & ( 1 << ( 7 - ( piece % 8 ) ) ) );
     148static inline int tr_bitfieldHas( tr_bitfield_t * bitfield, int piece )
     149{
     150    assert( piece / 8 < bitfield->len );
     151    return ( bitfield->bits[ piece / 8 ] & ( 1 << ( 7 - ( piece % 8 ) ) ) );
    110152}
    111153
     
    113155 * tr_bitfieldAdd
    114156 **********************************************************************/
    115 static inline void tr_bitfieldAdd( uint8_t * bitfield, int piece )
    116 {
    117     bitfield[ piece / 8 ] |= ( 1 << ( 7 - ( piece % 8 ) ) );
    118 }
    119 
    120 static inline void tr_bitfieldRem( uint8_t * bitfield, int piece )
    121 {
    122     bitfield[ piece / 8 ] &= ~( 1 << ( 7 - ( piece % 8 ) ) );
     157static inline void tr_bitfieldAdd( tr_bitfield_t * bitfield, int piece )
     158{
     159    assert( piece / 8 < bitfield->len );
     160    bitfield->bits[ piece / 8 ] |= ( 1 << ( 7 - ( piece % 8 ) ) );
     161}
     162
     163static inline void tr_bitfieldRem( tr_bitfield_t * bitfield, int piece )
     164{
     165    assert( piece / 8 < bitfield->len );
     166    bitfield->bits[ piece / 8 ] &= ~( 1 << ( 7 - ( piece % 8 ) ) );
    123167}
    124168
Note: See TracChangeset for help on using the changeset viewer.