diff --git a/include/opendht/indexation/pht.h b/include/opendht/indexation/pht.h index e8363074f..ee66ca519 100644 --- a/include/opendht/indexation/pht.h +++ b/include/opendht/indexation/pht.h @@ -200,6 +200,7 @@ ee * } std::string toString() const; + std::string flagsToString() const; size_t size_ {0}; @@ -239,7 +240,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 +257,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 dbda88f26..0e80cd731 100644 --- a/src/indexation/pht.cpp +++ b/src/indexation/pht.cpp @@ -25,39 +25,30 @@ 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 { - std::stringstream ss; - - ss << "Prefix : " << std::endl << "\tContent_ : \""; - ss << blobToString(content_); - ss << "\"" << std::endl; - - ss << "\tFlags_ : \""; - ss << blobToString(flags_); - ss << "\"" << std::endl; - - return ss.str(); -} +std::string Prefix::toString() const { return firstBitsToString(content_, size_); } +std::string Prefix::flagsToString() const { return firstBitsToString(flags_, size_); } void Pht::Cache::insert(const Prefix& p) { size_t i = 0;