/* */ #include "PieceStatMan.h" #include #include #include "SimpleRandomizer.h" #include "bitfield.h" namespace aria2 { PieceStatMan::PieceStatMan(size_t pieceNum, bool randomShuffle): order_(pieceNum), counts_(pieceNum) { for(size_t i = 0; i < pieceNum; ++i) { order_[i] = i; } // we need some randomness in ordering. if(randomShuffle) { std::random_shuffle(order_.begin(), order_.end(), *(SimpleRandomizer::getInstance().get())); } } PieceStatMan::~PieceStatMan() {} namespace { void inc(int& x) { if(x < std::numeric_limits::max()) { ++x; } } } // namespace namespace { void sub(int& x) { if(x > 0) { --x; } } } // namespace void PieceStatMan::addPieceStats(const unsigned char* bitfield, size_t bitfieldLength) { for(size_t i = 0, nbits = counts_.size(); i < nbits; ++i) { if(bitfield::test(bitfield, nbits, i)) { inc(counts_[i]); } } } void PieceStatMan::subtractPieceStats(const unsigned char* bitfield, size_t bitfieldLength) { for(size_t i = 0, nbits = counts_.size(); i < nbits; ++i) { if(bitfield::test(bitfield, nbits, i)) { sub(counts_[i]); } } } void PieceStatMan::updatePieceStats(const unsigned char* newBitfield, size_t newBitfieldLength, const unsigned char* oldBitfield) { for(size_t i = 0, nbits = counts_.size(); i < nbits; ++i) { bool inNew = bitfield::test(newBitfield, nbits, i); bool inOld = bitfield::test(oldBitfield, nbits, i); if(inNew) { if(!inOld) { inc(counts_[i]); } } else if(inOld) { sub(counts_[i]); } } } void PieceStatMan::addPieceStats(size_t index) { inc(counts_[index]); } } // namespace aria2