diff --git a/include/opendht/indexation/pht.h b/include/opendht/indexation/pht.h index e8363074f..deaea4524 100644 --- a/include/opendht/indexation/pht.h +++ b/include/opendht/indexation/pht.h @@ -239,7 +239,7 @@ ee * * @throw out_of_range if bit is superior to blob size * 8 */ bool isActiveBit(const Blob &b, size_t pos) const { - if ( pos >= content_.size() * 8 ) + if (pos >= content_.size() * 8) throw std::out_of_range("Can't detect active bit at pos, pos larger than prefix size or empty prefix"); return ((b[pos / 8] >> (7 - (pos % 8)) ) & 1) == 1; @@ -256,12 +256,14 @@ ee * * @throw out_of_range if bit is superior to blob size * 8 */ void swapBit(Blob &b, size_t bit) { - if ( bit >= b.size() * 8 ) + if (bit >= b.size() * 8) throw std::out_of_range("bit larger than prefix size."); size_t offset_bit = (8 - bit) % 8; b[bit / 8] ^= (1 << offset_bit); } + + std::string firstBitsToString(const Blob&, size_t) const; }; using Value = std::pair; diff --git a/src/indexation/pht.cpp b/src/indexation/pht.cpp index 719cba0d0..dfd93cdaa 100644 --- a/src/indexation/pht.cpp +++ b/src/indexation/pht.cpp @@ -25,26 +25,29 @@ namespace dht { namespace indexation { /** - * Output the blob into string and readable way + * Get bit string representation of a blob for a specified length. * - * @param bl : Blob to print + * @param bl A Blob + * @param len The number of bits to consider. * - * @return string that represent the blob into a readable way + * @return string that represent the blob */ -static std::string blobToString(const Blob &bl) { +std::string Prefix::firstBitsToString(const Blob &bl, size_t len) const { + if (len >= bl.size() * 8) + throw std::out_of_range("specified length larger than blob size"); std::stringstream ss; - auto bn = bl.size() % 8; - auto n = bl.size() / 8; + auto bn = len % 8; - for (size_t i = 0; i < bl.size(); i++) - ss << std::bitset<8>(bl[i]) << " "; + for (size_t i = 0; i < len/8; i++) + ss << std::bitset<8>(bl[i]); if (bn) - for (unsigned b=0; b < bn; b++) - ss << (char)((bl[n] & (1 << (7 - b))) ? '1':'0'); + for (unsigned b = 0; b < bn; b++) + ss << (char)((bl[len/8] & (1 << (7 - b))) ? '1':'0'); return ss.str(); } -std::string Prefix::toString() const { return blobToString(content_); } + +std::string Prefix::toString() const { return firstBitsToString(content_, size_); } void Pht::Cache::insert(const Prefix& p) { size_t i = 0;