Skip to content

Commit

Permalink
pht: rename and fix Pht::blobToString
Browse files Browse the repository at this point in the history
A refactoring error led to blobToString outputing garbage. This patch fixes the
issue and enables output of a number of bits other than multiple of 8.
  • Loading branch information
sim590 committed Apr 3, 2017
1 parent 574fd8e commit 625b09b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
6 changes: 4 additions & 2 deletions include/opendht/indexation/pht.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<InfoHash, dht::Value::Id>;
Expand Down
25 changes: 14 additions & 11 deletions src/indexation/pht.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 625b09b

Please sign in to comment.