Public Member Functions | Static Public Member Functions | Static Public Attributes | Private Member Functions | Private Attributes | Static Private Attributes | Friends

OverlayKey Class Reference

A common overlay key class. More...

#include <OverlayKey.h>

Inheritance diagram for OverlayKey:
P2pns::OverlayKeyObject

List of all members.

Public Member Functions

 OverlayKey ()
 Default constructor.
 OverlayKey (uint32_t num)
 Constructs an overlay key initialized with a common integer.
 OverlayKey (const unsigned char *buffer, uint32_t size)
 Constructs a key out of a buffer.
 OverlayKey (const std::string &str, uint32_t base=16)
 Constructs a key out of a string number.
 OverlayKey (const OverlayKey &rhs)
 Copy constructor.
 ~OverlayKey ()
 Default destructor.
std::string toString (uint32_t base=16) const
 Returns a string representation of this key.
bool isUnspecified () const
 Returns true, if the key is unspecified.
bool operator< (const OverlayKey &compKey) const
 compares this to a given OverlayKey
bool operator> (const OverlayKey &compKey) const
 compares this to a given OverlayKey
bool operator<= (const OverlayKey &compKey) const
 compares this to a given OverlayKey
bool operator>= (const OverlayKey &compKey) const
 compares this to a given OverlayKey
bool operator== (const OverlayKey &compKey) const
 compares this to a given OverlayKey
bool operator!= (const OverlayKey &compKey) const
 compares this to a given OverlayKey
int compareTo (const OverlayKey &compKey) const
 Unifies all compare operations in one method.
OverlayKeyoperator= (const OverlayKey &rhs)
 assigns OverlayKey of rhs to this->key
OverlayKeyoperator-- ()
 substracts 1 from this->key
OverlayKeyoperator++ ()
 adds 1 to this->key
OverlayKeyoperator+= (const OverlayKey &rhs)
 adds rhs->key to this->key
OverlayKeyoperator-= (const OverlayKey &rhs)
 substracts rhs->key from this->key
OverlayKey operator+ (const OverlayKey &rhs) const
 adds rhs->key to this->key
OverlayKey operator- (const OverlayKey &rhs) const
 substracts rhs->key from this->key
OverlayKey operator-- (int)
 substracts 1 from this->key
OverlayKey operator++ (int)
 adds 1 to this->key
OverlayKey operator>> (uint32_t num) const
 bitwise shift right
OverlayKey operator<< (uint32_t num) const
 bitwise shift left
OverlayKey operator& (const OverlayKey &rhs) const
 bitwise AND of rhs->key and this->key
OverlayKey operator| (const OverlayKey &rhs) const
 bitwise OR of rhs->key and this->key
OverlayKey operator^ (const OverlayKey &rhs) const
 bitwise XOR of rhs->key and this->key
OverlayKey operator~ () const
 bitwise NOT of this->key
OverlayKeyBit operator[] (uint32_t n)
 returns the n-th bit of this->key
OverlayKeysetBit (uint32_t pos, bool value)
 sets a bit of this->key
uint32_t getBitRange (uint32_t p, uint32_t n) const
 Returns a sub integer at position p with n-bits.
double toDouble () const
bool getBit (uint32_t p) const
size_t hash () const
 Returns a hash value for the key.
int log_2 () const
 Returns the position of the msb in this key, which represents just the logarithm to base 2.
OverlayKey randomSuffix (uint32_t pos) const
 Fills the suffix starting at pos with random bits to lsb.
OverlayKey randomPrefix (uint32_t pos) const
 Fills the prefix starting at pos with random bits to msb.
uint32_t sharedPrefixLength (const OverlayKey &compKey, uint32_t bitsPerDigit=1) const
 Calculates the number of equal bits (digits) from the left with another Key (shared prefix length).
bool isBetween (const OverlayKey &keyA, const OverlayKey &keyB) const
 Returns true, if this key is element of the interval (keyA, keyB) on the ring.
bool isBetweenR (const OverlayKey &keyA, const OverlayKey &keyB) const
 Returns true, if this key is element of the interval (keyA, keyB] on the ring.
bool isBetweenL (const OverlayKey &keyA, const OverlayKey &keyB) const
 Returns true, if this key is element of the interval [keyA, keyB) on the ring.
bool isBetweenLR (const OverlayKey &keyA, const OverlayKey &keyB) const
 Returns true, if this key is element of the interval [keyA, keyB] on the ring.
void netPack (cCommBuffer *b)
 serializes the object into a buffer
void netUnpack (cCommBuffer *b)
 deserializes the object from a buffer

Static Public Member Functions

static void setKeyLength (uint32_t length)
 Set the length of an OverlayKey.
static uint32_t getLength ()
 Returns the length in number of bits.
static OverlayKey random ()
 Returns a random key.
static OverlayKey getMax ()
 Returns the maximum key, i.e.
static OverlayKey sha1 (const BinaryValue &value)
 Returns a key with the SHA1 cryptographic hash of a BinaryValue.
static OverlayKey pow2 (uint32_t exponent)
 Returns a key 2^exponent.
static void test ()
 A pseudo regression test method.

Static Public Attributes

static const OverlayKey UNSPECIFIED_KEY
 OverlayKey without defined key.
static const OverlayKey ZERO
 OverlayKey with key initialized as 0.
static const OverlayKey ONE
 OverlayKey with key initialized as 1.

Private Member Functions

void trim ()
 trims key after key operations
void clear ()
 set this->key to 0 and isUnspec to false

Private Attributes

bool isUnspec
 is this->key unspecified?
mp_limb_t key [MAX_KEYLENGTH/(8 *sizeof(mp_limb_t))+(MAX_KEYLENGTH%(8 *sizeof(mp_limb_t))!=0?1:0)]
 the overlay key this object represents

Static Private Attributes

static const uint32_t MAX_KEYLENGTH = 160
 maximum length of the key
static uint32_t keyLength = MAX_KEYLENGTH
 actual length of the key
static uint32_t aSize
 number of needed machine words to hold the key
static mp_limb_t GMP_MSB_MASK
 bits to fill up if key does not exactly fit in one or more machine words

Friends

std::ostream & operator<< (std::ostream &os, const OverlayKey &c)
 Common stdc++ console output method.

Detailed Description

A common overlay key class.

Wraps common functions from Gnu MP library.

Author:
Sebastian Mies.

Definition at line 46 of file OverlayKey.h.


Constructor & Destructor Documentation

OverlayKey::OverlayKey (  ) 

Default constructor.

Contructs an unspecified overlay key

Definition at line 67 of file OverlayKey.cc.

Referenced by sha1().

{
    isUnspec = true;
}

OverlayKey::OverlayKey ( uint32_t  num  ) 

Constructs an overlay key initialized with a common integer.

Parameters:
num The integer to initialize this key with

Definition at line 73 of file OverlayKey.cc.

{
    clear();
    key[0] = num;
    trim();
}

OverlayKey::OverlayKey ( const unsigned char *  buffer,
uint32_t  size 
)

Constructs a key out of a buffer.

Parameters:
buffer Source buffer
size Buffer size (in bytes)

Definition at line 81 of file OverlayKey.cc.

{
    int trimSize, offset;
    clear();
    trimSize = (int)min((uint32_t) (aSize * sizeof(mp_limb_t)), size);
    offset = aSize * sizeof(mp_limb_t) - trimSize;
    memcpy( ((char*)key) + offset, buf, trimSize);
    trim();
}

OverlayKey::OverlayKey ( const std::string &  str,
uint32_t  base = 16 
)

Constructs a key out of a string number.

Definition at line 92 of file OverlayKey.cc.

{
    if ((base < 2) || (base > 16)) {
        throw cRuntimeError("OverlayKey::OverlayKey(): Invalid base!");
    }

    string s(str);
    clear();

    for (uint32_t i=0; i<s.size(); i++) {
        if ((s[i] >= '0') && (s[i] <= '9')) {
            s[i] -= '0';
        } else if ((s[i] >= 'a') && (s[i] <= 'f')) {
            s[i] -= ('a' - 10);
        } else if ((s[i] >= 'A') & (s[i] <= 'F')) {
            s[i] -= ('A' - 10);
        } else {
            throw cRuntimeError("OverlayKey::OverlayKey(): "
                                    "Invalid character in string!");
        }
    }

    mpn_set_str ((mp_limb_t*)this->key, (const unsigned char*)s.c_str(),
                 str.size(), base);
    trim();
}

OverlayKey::OverlayKey ( const OverlayKey rhs  ) 

Copy constructor.

Parameters:
rhs The key to copy.

Definition at line 120 of file OverlayKey.cc.

{
    (*this) = rhs;
}

OverlayKey::~OverlayKey (  ) 

Default destructor.

Does nothing ATM.

Definition at line 126 of file OverlayKey.cc.

{}


Member Function Documentation

void OverlayKey::clear (  )  [inline, private]

set this->key to 0 and isUnspec to false

Definition at line 814 of file OverlayKey.cc.

Referenced by OverlayKey().

{
    memset( key, 0, aSize * sizeof(mp_limb_t) );
    isUnspec = false;
}

int OverlayKey::compareTo ( const OverlayKey compKey  )  const

Unifies all compare operations in one method.

Parameters:
compKey key to compare with
Returns:
int -1 if smaller, 0 if equal, 1 if greater

Definition at line 806 of file OverlayKey.cc.

Referenced by IterativeLookup::compare(), KademliaPRComparator::compare(), operator!=(), operator<(), NodeHandle::operator<(), operator<=(), operator==(), operator>(), NodeHandle::operator>(), operator>=(), and sharedPrefixLength().

{
    if (compKey.isUnspec || isUnspec)
        opp_error("OverlayKey::compareTo(): key is unspecified!");
    return mpn_cmp(key,compKey.key,aSize);
}

bool OverlayKey::getBit ( uint32_t  p  )  const [inline]
uint32_t OverlayKey::getBitRange ( uint32_t  p,
uint32_t  n 
) const

Returns a sub integer at position p with n-bits.

p is counted starting from the least significant bit of the key as bit 0. Bit p of the key becomes bit 0 of the returned integer.

Parameters:
p the position of the sub-integer
n the number of bits to be returned (max.32)
Returns:
The sub-integer.

Definition at line 424 of file OverlayKey.cc.

Referenced by PastryRoutingTable::digitAt(), Bamboo::doGlobalTuning(), getBit(), XmlRpcInterface::handleReadyMessage(), Kademlia::routingBucketIndex(), test(), toDouble(), and toString().

{
    int i = p / GMP_LIMB_BITS,      // index of starting bit
        f = p % GMP_LIMB_BITS,      // position of starting bit
        f2 = f + n - GMP_LIMB_BITS; // how many bits to take from next index

    if ((p + n > OverlayKey::keyLength) || (n > 32)) {
        throw cRuntimeError("OverlayKey::get:  Invalid range");
    }
    if (GMP_LIMB_BITS < 32) {
        throw cRuntimeError("OverlayKey::get:  GMP_LIMB_BITS too small!");
    }

    return ((key[i] >> f) |                                     // get the bits of key[i]
            (f2 > 0 ? (key[i+1] << (GMP_LIMB_BITS - f)) : 0)) & // the extra bits from key[i+1]
        (((uint32_t)(~0)) >> (GMP_LIMB_BITS - n));              // delete unused bits
}

OverlayKey OverlayKey::getMax (  )  [static]

Returns the maximum key, i.e.

a key filled with bit 1

Returns:
The maximum key, i.e. a key filled with bit 1

Definition at line 625 of file OverlayKey.cc.

Referenced by PastryStateObject::keyDist(), and test().

{
    OverlayKey newKey;

    for (uint32_t i=0; i<aSize; i++) {
        newKey.key[i] = ~0;
    }
    newKey.isUnspec = false;
    newKey.trim();

    return newKey;
}

size_t OverlayKey::hash (  )  const

Returns a hash value for the key.

Returns:
size_t The hash value

Definition at line 547 of file OverlayKey.cc.

{
    return (size_t)key[0];
}

bool OverlayKey::isBetween ( const OverlayKey keyA,
const OverlayKey keyB 
) const

Returns true, if this key is element of the interval (keyA, keyB) on the ring.

Parameters:
keyA The left border of the interval
keyB The right border of the interval
Returns:
True, if the key is element of the interval (keyA, keyB)

Definition at line 553 of file OverlayKey.cc.

Referenced by oversim::Chord::closestPreceedingNode(), oversim::Koorde::findDeBruijnHop(), oversim::Chord::handleRpcStabilizeResponse(), PastryLeafSet::mergeNode(), oversim::Chord::rpcNotify(), and test().

{
    if (isUnspec || keyA.isUnspec || keyB.isUnspec)
        return false;

    if (*this == keyA)
        return false;
    else if (keyA < keyB)
        return ((*this > keyA) && (*this < keyB));
    else
        return ((*this > keyA) || (*this < keyB));
}

bool OverlayKey::isBetweenL ( const OverlayKey keyA,
const OverlayKey keyB 
) const

Returns true, if this key is element of the interval [keyA, keyB) on the ring.

Parameters:
keyA The left border of the interval
keyB The right border of the interval
Returns:
True, if the key is element of the interval [keyA, keyB)

Definition at line 583 of file OverlayKey.cc.

Referenced by test().

{
    if (isUnspec || keyA.isUnspec || keyB.isUnspec)
        return false;

    if ((keyA == keyB) && (*this == keyA))
        return true;
    else if (keyA <= keyB)
        return ((*this >= keyA) && (*this < keyB));
    else
        return ((*this >= keyA) || (*this < keyB));
}

bool OverlayKey::isBetweenLR ( const OverlayKey keyA,
const OverlayKey keyB 
) const

Returns true, if this key is element of the interval [keyA, keyB] on the ring.

Parameters:
keyA The left border of the interval
keyB The right border of the interval
Returns:
True, if the key is element of the interval [keyA, keyB]

Definition at line 598 of file OverlayKey.cc.

Referenced by oversim::Chord::closestPreceedingNode(), PastryLeafSet::getDestinationNode(), oversim::ChordFingerTable::getFinger(), and oversim::ChordSuccessorList::updateList().

{
    if (isUnspec || keyA.isUnspec || keyB.isUnspec)
        return false;

    if ((keyA == keyB) && (*this == keyA))
        return true;
    else if (keyA <= keyB)
        return ((*this >= keyA) && (*this <= keyB));
    else
        return ((*this >= keyA) || (*this <= keyB));
}

bool OverlayKey::isBetweenR ( const OverlayKey keyA,
const OverlayKey keyB 
) const

Returns true, if this key is element of the interval (keyA, keyB] on the ring.

Parameters:
keyA The left border of the interval
keyB The right border of the interval
Returns:
True, if the key is element of the interval (keyA, keyB]

Definition at line 568 of file OverlayKey.cc.

Referenced by oversim::Chord::closestPreceedingNode(), oversim::Koorde::findDeBruijnHop(), oversim::Koorde::findNode(), oversim::Chord::findNode(), oversim::Koorde::handleDeBruijnTimerExpired(), oversim::Koorde::handleRpcDeBruijnRequest(), oversim::Chord::isSiblingFor(), test(), oversim::Koorde::walkDeBruijnList(), and oversim::Koorde::walkSuccessorList().

{
    if (isUnspec || keyA.isUnspec || keyB.isUnspec)
        return false;

    if ((keyA == keyB) && (*this == keyA))
        return true;
    else if (keyA <= keyB)
        return ((*this > keyA) && (*this <= keyB));
    else
        return ((*this > keyA) || (*this <= keyB));
}

int OverlayKey::log_2 (  )  const

Returns the position of the msb in this key, which represents just the logarithm to base 2.

Returns:
The logarithm to base 2 of this key.

Definition at line 524 of file OverlayKey.cc.

Referenced by oversim::Koorde::findStartKey().

{
    int16_t i = aSize-1;

    while (i>=0 && key[i]==0) {
        i--;
    }

    if (i<0) {
        return -1;
    }

    mp_limb_t j = key[i];
    i *= GMP_LIMB_BITS;
    while (j!=0) {
        j >>= 1;
        i++;
    }

    return i-1;
}

void OverlayKey::netPack ( cCommBuffer *  b  ) 

serializes the object into a buffer

Parameters:
b the buffer

Definition at line 841 of file OverlayKey.cc.

Referenced by doPacking().

{
    //doPacking(b,(GMP_TYPE*)this->key, MAX_KEYLENGTH / (8*sizeof(mp_limb_t)) +
              //(MAX_KEYLENGTH % (8*sizeof(mp_limb_t))!=0 ? 1 : 0));
    // Pack an OverlayKey as uint32_t array and hope for the best
    // FIXME: This is probably not exactly portable
    doPacking(b,(uint32_t*)this->key, MAX_KEYLENGTH / (8*sizeof(uint32_t)) +
              (MAX_KEYLENGTH % (8*sizeof(uint32_t))!=0 ? 1 : 0));
    doPacking(b,this->isUnspec);
}

void OverlayKey::netUnpack ( cCommBuffer *  b  ) 

deserializes the object from a buffer

Parameters:
b the buffer

Definition at line 852 of file OverlayKey.cc.

Referenced by doUnpacking().

{
    //doUnpacking(b,(GMP_TYPE*)this->key, MAX_KEYLENGTH / (8*sizeof(mp_limb_t)) +
                //(MAX_KEYLENGTH % (8*sizeof(mp_limb_t))!=0 ? 1 : 0));
    doUnpacking(b,(uint32_t*)this->key, MAX_KEYLENGTH / (8*sizeof(uint32_t)) +
                (MAX_KEYLENGTH % (8*sizeof(uint32_t))!=0 ? 1 : 0));
    doUnpacking(b,this->isUnspec);

}

bool OverlayKey::operator!= ( const OverlayKey compKey  )  const

compares this to a given OverlayKey

Parameters:
compKey the the OverlayKey to compare this to
Returns:
true if compKey->key is not equal to this->key, else false

Definition at line 301 of file OverlayKey.cc.

{
    return compareTo(compKey) !=0;
}

OverlayKey OverlayKey::operator& ( const OverlayKey rhs  )  const

bitwise AND of rhs->key and this->key

Parameters:
rhs the OverlayKey AND is calculated with
Returns:
this OverlayKey object

Definition at line 329 of file OverlayKey.cc.

{
    OverlayKey result = *this;
    for (uint32_t i=0; i<aSize; i++) {
        result.key[i] &= rhs.key[i];
    }

    return result;
}

OverlayKey OverlayKey::operator+ ( const OverlayKey rhs  )  const

adds rhs->key to this->key

Parameters:
rhs the OverlayKey with the defined key
Returns:
this OverlayKey object

Definition at line 265 of file OverlayKey.cc.

{
    OverlayKey result = *this;
    result += rhs;
    return result;
}

OverlayKey OverlayKey::operator++ ( int   ) 

adds 1 to this->key

Returns:
this OverlayKey object

Definition at line 239 of file OverlayKey.cc.

{
    OverlayKey clone = *this;
    *this += ONE;
    return clone;
}

OverlayKey & OverlayKey::operator++ (  ) 

adds 1 to this->key

Returns:
this OverlayKey object

Definition at line 233 of file OverlayKey.cc.

{
    return (*this += ONE);
}

OverlayKey & OverlayKey::operator+= ( const OverlayKey rhs  ) 

adds rhs->key to this->key

Parameters:
rhs the OverlayKey with the defined key
Returns:
this OverlayKey object

Definition at line 247 of file OverlayKey.cc.

{
    mpn_add_n((mp_limb_t*)key, (mp_limb_t*)key, (mp_limb_t*)rhs.key, aSize);
    trim();
    isUnspec = false;
    return *this;
}

OverlayKey OverlayKey::operator- ( const OverlayKey rhs  )  const

substracts rhs->key from this->key

Parameters:
rhs the OverlayKey with the defined key
Returns:
this OverlayKey object

Definition at line 273 of file OverlayKey.cc.

{
    OverlayKey result = *this;
    result -= rhs;
    return result;
}

OverlayKey OverlayKey::operator-- ( int   ) 

substracts 1 from this->key

Returns:
this OverlayKey object

Definition at line 225 of file OverlayKey.cc.

{
    OverlayKey clone = *this;
    *this -= ONE;
    return clone;
}

OverlayKey & OverlayKey::operator-- (  ) 

substracts 1 from this->key

Returns:
this OverlayKey object

Definition at line 219 of file OverlayKey.cc.

{
    return (*this -= ONE);
}

OverlayKey & OverlayKey::operator-= ( const OverlayKey rhs  ) 

substracts rhs->key from this->key

Parameters:
rhs the OverlayKey with the defined key
Returns:
this OverlayKey object

Definition at line 256 of file OverlayKey.cc.

{
    mpn_sub_n((mp_limb_t*)key, (mp_limb_t*)key, (mp_limb_t*)rhs.key, aSize);
    trim();
    isUnspec = false;
    return *this;
}

bool OverlayKey::operator< ( const OverlayKey compKey  )  const

compares this to a given OverlayKey

Parameters:
compKey the the OverlayKey to compare this to
Returns:
true if compKey->key is smaller than this->key, else false

Definition at line 281 of file OverlayKey.cc.

{
    return compareTo(compKey) < 0;
}

OverlayKey OverlayKey::operator<< ( uint32_t  num  )  const

bitwise shift left

Parameters:
num number of bits to shift
Returns:
this OverlayKey object

Definition at line 373 of file OverlayKey.cc.

{
    OverlayKey result = ZERO;
    int i = num/GMP_LIMB_BITS;

    num %= GMP_LIMB_BITS;

    if (i>=(int)aSize)
        return result;

    for (int j=0; j<(int)aSize-i; j++) {
        result.key[j+i] = key[j];
    }
    mpn_lshift(result.key,result.key,aSize,num);
    result.isUnspec = false;
    result.trim();

    return result;
}

bool OverlayKey::operator<= ( const OverlayKey compKey  )  const

compares this to a given OverlayKey

Parameters:
compKey the the OverlayKey to compare this to
Returns:
true if compKey->key is smaller than or equal to this->key, else false

Definition at line 289 of file OverlayKey.cc.

{
    return compareTo(compKey) <=0;
}

OverlayKey & OverlayKey::operator= ( const OverlayKey rhs  ) 

assigns OverlayKey of rhs to this->key

Parameters:
rhs the OverlayKey with the defined key
Returns:
this OverlayKey object

Definition at line 211 of file OverlayKey.cc.

{
    isUnspec = rhs.isUnspec;
    memcpy( key, rhs.key, aSize*sizeof(mp_limb_t) );
    return *this;
}

bool OverlayKey::operator== ( const OverlayKey compKey  )  const

compares this to a given OverlayKey

Parameters:
compKey the the OverlayKey to compare this to
Returns:
true if compKey->key is equal to this->key, else false

Definition at line 297 of file OverlayKey.cc.

{
    return compareTo(compKey) ==0;
}

bool OverlayKey::operator> ( const OverlayKey compKey  )  const

compares this to a given OverlayKey

Parameters:
compKey the the OverlayKey to compare this to
Returns:
true if compKey->key is greater than this->key, else false

Definition at line 285 of file OverlayKey.cc.

{
    return compareTo(compKey) > 0;
}

bool OverlayKey::operator>= ( const OverlayKey compKey  )  const

compares this to a given OverlayKey

Parameters:
compKey the the OverlayKey to compare this to
Returns:
true if compKey->key is greater than or equal to this->key, else false

Definition at line 293 of file OverlayKey.cc.

{
    return compareTo(compKey) >=0;
}

OverlayKey OverlayKey::operator>> ( uint32_t  num  )  const

bitwise shift right

Parameters:
num number of bits to shift
Returns:
this OverlayKey object

Definition at line 352 of file OverlayKey.cc.

{
    OverlayKey result = ZERO;
    int i = num/GMP_LIMB_BITS;

    num %= GMP_LIMB_BITS;

    if (i>=(int)aSize)
        return result;

    for (int j=0; j<(int)aSize-i; j++) {
        result.key[j] = key[j+i];
    }
    mpn_rshift(result.key,result.key,aSize,num);
    result.isUnspec = false;
    result.trim();

    return result;
}

OverlayKeyBit OverlayKey::operator[] ( uint32_t  n  ) 

returns the n-th bit of this->key

Parameters:
n the position of the returned bit
Returns:
the bit on position n in this->key

Definition at line 394 of file OverlayKey.cc.

{
    return OverlayKeyBit(getBit(n), n, this);
}

OverlayKey OverlayKey::operator^ ( const OverlayKey rhs  )  const

bitwise XOR of rhs->key and this->key

Parameters:
rhs the OverlayKey XOR is calculated with
Returns:
this OverlayKey object

Definition at line 307 of file OverlayKey.cc.

{
    OverlayKey result = *this;
    for (uint32_t i=0; i<aSize; i++) {
        result.key[i] ^= rhs.key[i];
    }

    return result;
}

OverlayKey OverlayKey::operator| ( const OverlayKey rhs  )  const

bitwise OR of rhs->key and this->key

Parameters:
rhs the OverlayKey OR is calculated with
Returns:
this OverlayKey object

Definition at line 318 of file OverlayKey.cc.

{
    OverlayKey result = *this;
    for (uint32_t i=0; i<aSize; i++) {
        result.key[i] |= rhs.key[i];
    }

    return result;
}

OverlayKey OverlayKey::operator~ (  )  const

bitwise NOT of this->key

Returns:
this OverlayKey object

Definition at line 340 of file OverlayKey.cc.

{
    OverlayKey result = *this;
    for (uint32_t i=0; i<aSize; i++) {
        result.key[i] = ~key[i];
    }
    result.trim();

    return result;
}

OverlayKey OverlayKey::pow2 ( uint32_t  exponent  )  [static]

Returns a key 2^exponent.

Parameters:
exponent The exponent.
Returns:
Key=2^exponent.

Definition at line 670 of file OverlayKey.cc.

Referenced by oversim::Koorde::findStartKey(), oversim::Chord::handleFixFingersTimerExpired(), oversim::Chord::handleStabilizeTimerExpired(), and test().

{
    if (exponent >= keyLength) {
        throw cRuntimeError("OverlayKey::pow2(): "
                                "exponent >= keyLength!");
    }

    OverlayKey newKey = ZERO;

    newKey.key[exponent/GMP_LIMB_BITS] =
        (mp_limb_t)1 << (exponent % GMP_LIMB_BITS);

    return newKey;
}

OverlayKey OverlayKey::randomPrefix ( uint32_t  pos  )  const

Fills the prefix starting at pos with random bits to msb.

Parameters:
pos 
Returns:
OverlayKey

Definition at line 474 of file OverlayKey.cc.

Referenced by CoordBasedRouting::getNodeId(), and test().

{
    OverlayKey newKey = *this;
    int i = pos/GMP_LIMB_BITS, j = pos%GMP_LIMB_BITS;
    mp_limb_t m = ((mp_limb_t)1 << j)-1;
    mp_limb_t rnd;

    //  mpn_random(&rnd,1);
    omnet_random(&rnd,1);

    newKey.key[i] &= m;
    newKey.key[i] |= (rnd&~m);
    for (int k=aSize-1; k!=i; k--) {
        //        mpn_random( &newKey.key[k], 1 );
        omnet_random( &newKey.key[k], 1 );
    }
    newKey.trim();

    return newKey;
}

OverlayKey OverlayKey::randomSuffix ( uint32_t  pos  )  const

Fills the suffix starting at pos with random bits to lsb.

Parameters:
pos 
Returns:
OverlayKey

Definition at line 455 of file OverlayKey.cc.

Referenced by CoordBasedRouting::getNodeId(), and test().

{
    OverlayKey newKey = *this;
    int i = pos/GMP_LIMB_BITS, j = pos%GMP_LIMB_BITS;
    mp_limb_t m = ((mp_limb_t)1 << j)-1;
    mp_limb_t rnd;

    //  mpn_random(&rnd,1);
    omnet_random(&rnd,1);
    newKey.key[i] &= ~m;
    newKey.key[i] |= (rnd&m);
    //  mpn_random(newKey.key,i);
    omnet_random(newKey.key,i);
    newKey.trim();

    return newKey;
}

OverlayKey & OverlayKey::setBit ( uint32_t  pos,
bool  value 
)

sets a bit of this->key

Parameters:
pos the position of the bit to set
value new value for bit at position pos
Returns:
*this

Definition at line 399 of file OverlayKey.cc.

Referenced by OverlayKeyBit::operator=(), and OverlayKeyBit::operator^=().

{
    if (pos >= keyLength) {
        throw cRuntimeError("OverlayKey::setBitAt(): "
                                "pos >= keyLength!");
    }

    mp_limb_t digit = 1;
    digit = digit << (pos % GMP_LIMB_BITS);

    if (value) {
        key[pos / GMP_LIMB_BITS] |= digit;
    } else {
        //key[pos / GMP_LIMB_BITS] = key[pos / GMP_LIMB_BITS] & ~digit;
        key[pos / GMP_LIMB_BITS] &= ~digit;
    }

    return *this;
};

void OverlayKey::setKeyLength ( uint32_t  length  )  [static]

Set the length of an OverlayKey.

Parameters:
length keylength in bits

Definition at line 133 of file OverlayKey.cc.

Referenced by BaseOverlay::initialize().

{
    if ((length < 1) || (length > OverlayKey::keyLength)) {
        opp_error("OverlayKey::setKeyLength(): length must be <= %i "
                  "and setKeyLength() must not be called twice "
                  "with different length!", MAX_KEYLENGTH);
    }

    keyLength = length;

    aSize = keyLength / (8*sizeof(mp_limb_t)) +
        (keyLength % (8*sizeof(mp_limb_t))!=0 ? 1 : 0);

    GMP_MSB_MASK = (keyLength % GMP_LIMB_BITS)
        != 0 ? (((mp_limb_t)1 << (keyLength % GMP_LIMB_BITS))-1)
        : (mp_limb_t)-1;
}

OverlayKey OverlayKey::sha1 ( const BinaryValue value  )  [static]

Returns a key with the SHA1 cryptographic hash of a BinaryValue.

Parameters:
value A BinaryValue object.
Returns:
SHA1 of value

Definition at line 651 of file OverlayKey.cc.

Referenced by XmlRpcInterface::get(), CBRDHT::handleGetCAPIRequest(), SimMud::handleMove(), CBRDHT::handlePutCAPIRequest(), DHTTestApp::handleTraceMessage(), RealWorldTestApp::handleUpperMessage(), XmlRpcInterface::joinOverlay(), XmlRpcInterface::localLookup(), XmlRpcInterface::lookup(), P2pns::p2pnsRegisterRpc(), P2pns::p2pnsResolveRpc(), XmlRpcInterface::put(), P2pns::registerId(), and test().

{
    OverlayKey newKey = OverlayKey();
    uint8_t temp[20];
    CSHA1 sha1;

    sha1.Reset();
    sha1.Update((uint8_t*)(&(*input.begin())), input.size());
    sha1.Final();
    sha1.GetHash(temp);
    mpn_set_str(newKey.key, (const uint8_t*)temp,
                (int)std::min((uint32_t)(aSize * sizeof(mp_limb_t)), 20U), 256);
    newKey.isUnspec = false;
    newKey.trim();

    return newKey;
}

uint32_t OverlayKey::sharedPrefixLength ( const OverlayKey compKey,
uint32_t  bitsPerDigit = 1 
) const

Calculates the number of equal bits (digits) from the left with another Key (shared prefix length).

Parameters:
compKey the Key to compare with
bitsPerDigit optional number of bits per digit, default is 1
Returns:
length of shared prefix

Definition at line 496 of file OverlayKey.cc.

Referenced by KeyPrefixMetric::distance(), PastryRoutingTable::findCloserNode(), oversim::Koorde::findStartKey(), Broose::getRoutingDistance(), P2pns::handleTunnelLookupResponse(), PastryRoutingTable::lookupNextHop(), PastryRoutingTable::mergeNode(), PastryStateObject::specialCloserCondition(), and test().

{
    if (compareTo(compKey) == 0) return keyLength;

    uint32_t length = 0;
    int i;
    uint32_t j;
    bool msb = true;

    // count equal limbs first:
    for (i=aSize-1; i>=0; --i) {
        if (this->key[i] != compKey.key[i]) {
            // XOR first differing limb for easy counting of the bits:
            mp_limb_t d = this->key[i] ^ compKey.key[i];
            if (msb) d <<= ( GMP_LIMB_BITS - (keyLength % GMP_LIMB_BITS) );
            for (j = GMP_LIMB_BITS-1; d >>= 1; --j);
            length += j;
            break;
        }
        length += GMP_LIMB_BITS;
        msb = false;
    }

    return length / bitsPerDigit;
}

void OverlayKey::test (  )  [static]

A pseudo regression test method.

Outputs report to standard output.

Definition at line 686 of file OverlayKey.cc.

{
    // add test
    cout << endl << "--- Add test ..." << endl;
    OverlayKey key = 123456789;
    cout << "    key=" << key << endl;
    cout << "    key += 987654321 = " << (key+=987654321) << endl;
    cout << "    prefix++  : " << (++key) << endl;
    cout << "    postfix++ : " << (key++) << endl;
    cout << "    key=" << key << endl;

    OverlayKey k1 = 256, k2 = 10, k3 = 3;

    // compare test
    cout << endl << "--- Compare test ..." << endl;
    cout << "    256 < 10 = "<< (k1 < k2) << " k1="<<k1<<endl;
    cout << "    256 > 10 = "<< (k1 > k2) << " k2="<<k2<<endl;

    cout << "    10 isBetween(3, 256)=" << k2.isBetween(k3, k1) << endl;
    cout << "    3 isBetween(10, 256)=" << k3.isBetween(k2, k1) << endl;
    cout << "    256 isBetween(10, 256)=" << k1.isBetween(k2, k1) << endl;
    cout << "    256 isBetweenR(10, 256)=" << k1.isBetweenR(k2, k1) << endl;
    cout << "    max isBetween(max-1,0)=" << OverlayKey::getMax().isBetween(
                                                                         OverlayKey::getMax()-1, OverlayKey::ZERO) << endl;
    cout << "    max-1 isBetween(max,1)=" << (OverlayKey::getMax()-1).isBetween(
                                                                             OverlayKey::getMax(), OverlayKey::ONE) << endl;
    cout << "    max-1 isBetweenL(max-1,1)=" << (OverlayKey::getMax()-1).
        isBetweenL(OverlayKey::getMax()-1, OverlayKey::ONE) << endl;
    cout << "    1 isBetweenL(max-1,1)=" << (OverlayKey::ONE).isBetweenL(
                                                                         OverlayKey::getMax()-1, OverlayKey::ONE) << endl;
    cout << "    1 isBetweenR(max-1,1)=" << OverlayKey::ONE.isBetweenR(
                                                                       OverlayKey::getMax()-1, OverlayKey::ONE) << endl;
    cout << "    1 isBetween(max-1,1)=" << OverlayKey::ONE.isBetween(
                                                                     OverlayKey::getMax()-1, OverlayKey::ONE) << endl;
    cout << "    1 isBetween(max-1,0)=" << OverlayKey::ONE.isBetween(
                                                                     OverlayKey::getMax()-1, OverlayKey::ZERO) << endl;
    cout << "    256 sharedPrefixLength(3)=" << k1.sharedPrefixLength(k3)
         << endl;
    cout << "    256 sharedPrefixLength(256)=" << k1.sharedPrefixLength(k1)
         << endl;

    // wrap around test
    cout << endl << "--- Warp around test ..." << endl;

    k1 = OverlayKey::getMax();
    cout << "k1=max= " << k1.toString(16) << endl;
    cout << "k1+1 = " << (k1 + 1).toString(16) << endl;
    cout << "k1+2 = " << (k1 + 2).toString(16) << endl;

    k1 = OverlayKey::ZERO;
    cout << "k1=0= " << k1.toString(16) << endl;
    cout << "k1-1 = " << (k1 - 1).toString(16) << endl;
    cout << "k1-2 = " << (k1 - 2).toString(16) << endl;

    cout << "max > ONE=" << (OverlayKey::getMax() > OverlayKey::ONE) << endl;
    cout << "max < ONE=" << (OverlayKey::getMax() < OverlayKey::ONE) << endl;

    // distance test
    cout << endl << "--- Distance test ..." << endl;

    cout << "KeyRingMetric::distance(1, max)="
         <<  KeyRingMetric().distance(OverlayKey::ONE, OverlayKey::getMax()) << endl;
    cout << "KeyUniRingMetric::distance(1, max)="
         <<  KeyUniRingMetric().distance(OverlayKey::ONE, OverlayKey::getMax()) << endl;
    cout << "KeyRingMetric::distance(max, 1)="
         <<  KeyRingMetric().distance(OverlayKey::getMax(), OverlayKey::ONE) << endl;
    cout << "KeyUniRingMetric::distance(max, 1)="
         <<  KeyUniRingMetric().distance(OverlayKey::getMax(), OverlayKey::ONE) << endl;

    // suffix and log2 test
    cout << endl << "--- RandomSuffix and log2 test ..." << endl;
    k1 = OverlayKey::ZERO;
    for (uint32_t i=0; i<k1.getLength(); i++) {
        k2=k1.randomSuffix(i);
        cout << "    " << k2.toString(16) << " log2=" << k2.log_2() << endl;
    }
    cout << endl << "--- RandomPrefix and log2 test ..." << endl;
    k1 = OverlayKey::getMax();
    for (uint32_t i=0; i<k1.getLength(); i++) {
        k2=k1.randomPrefix(i);
        cout << "    " << k2.toString(16) << " log2=" << k2.log_2() << endl;
    }

    cout << endl << "--- pow2 test..." << endl;
    for (uint32_t i=0; i<k1.getLength(); i++) {
        k2=pow2(i);
        cout << " 2^" << i << " = " << k2.toString(16) << "   log2="
             << k2.log_2() << endl;
    }

    cout << endl << "--- Bits test ..." << endl << "    ";
    const char* BITS[] = { "000","001","010","011","100","101","110","111" };
    k1 = OverlayKey::random();
    for (int i=k1.getLength()-1; i>=0; i--)
        cout << k1[i];
    cout << " = " << endl << "    ";
    for (int i=k1.getLength()-3; i>=0; i-=3)
        cout << BITS[k1.getBitRange(i,3)];
    cout << endl;

    cout << endl << "--- SHA1 test ... (verified with test vectors)" << endl;
    cout << "    Empty string: " << OverlayKey::sha1("").toString(16)
         << " = da39a3ee5e6b4b0d3255bfef95601890afd80709" << endl;
    cout << "    'Hello World' string: "
         << OverlayKey::sha1("Hello World").toString(16)
         << " = 0a4d55a8d778e5022fab701977c5d840bbc486d0" << endl;
}

double OverlayKey::toDouble (  )  const

Definition at line 442 of file OverlayKey.cc.

{
    double result = 0;
    uint8_t range = 32, length = getLength();
    for (uint8_t i = 0; i < length; i += 32) {
        if ((length - i) < 32) range = length - i;
        result += (getBitRange(i, range) * pow(2.0, i));
    }

    return result;
}

std::string OverlayKey::toString ( uint32_t  base = 16  )  const

Returns a string representation of this key.

Returns:
String representation of this key

Definition at line 163 of file OverlayKey.cc.

Referenced by IterativeLookup::addSibling(), Quon::addSite(), BasePastry::baseInit(), BaseOverlay::bindToPort(), BaseApp::callRoute(), BaseOverlay::callUpdate(), Vast::changeState(), Quon::changeState(), oversim::Chord::changeState(), NTree::checkParentTimeout(), Pastry::checkProxCache(), oversim::Chord::closestPreceedingNode(), NTree::collapseTree(), Nps::coordsReqRpcResponse(), Quon::deleteSite(), KBRTestApp::deliver(), Broose::displayBucketState(), NTree::divideNode(), Bamboo::doLocalTuning(), Pastry::doRoutingTableMaintenance(), Pastry::doSecondStage(), BaseOverlay::findNodeRpc(), oversim::Koorde::findStartKey(), Gia::forwardMessage(), CoordBasedRouting::getEuclidianDistanceByKeyAndCoords(), NTree::handleAddMessage(), PubSubMMOG::handleAdoptChildCall(), PubSubMMOG::handleAdoptChildResponse(), Vast::handleAppMessage(), Quon::handleAppMessage(), oversim::Nice::handleAppMessage(), BaseOverlay::handleBaseOverlayMessage(), NTree::handleCollapseMessage(), BaseApp::handleCommonAPIMessage(), NTree::handleDivideCall(), Pastry::handleFailedNode(), CBRDHT::handleGetCAPIRequest(), DHT::handleGetRequest(), CBRDHT::handleGetRequest(), PubSubMMOG::handleHelpResponse(), PubSubMMOG::handleIntermediateResponse(), NTree::handleJoinCall(), Scribe::handleJoinMessage(), Scribe::handleJoinResponse(), NTree::handleJoinResponse(), KBRTestApp::handleLookupResponse(), BootstrapList::handleLookupResponse(), XmlRpcInterface::handleMessage(), BaseOverlay::handleMessage(), BaseApp::handleMessage(), NTree::handleMove(), PubSubMMOG::handleMoveMessage(), Vast::handleNodeLeaveNotification(), PubSubMMOG::handlePingCall(), Scribe::handlePublishCall(), Scribe::handlePublishResponse(), CBRDHT::handlePutCAPIRequest(), DHT::handlePutRequest(), CBRDHT::handlePutRequest(), NTree::handleReplaceMessage(), BasePastry::handleRequestMessage(), oversim::Koorde::handleRpcCall(), oversim::Chord::handleRpcCall(), oversim::Chord::handleRpcNotifyResponse(), Scribe::handleRpcResponse(), PubSubMMOG::handleRpcResponse(), NTree::handleRpcResponse(), oversim::Koorde::handleRpcResponse(), KBRTestApp::handleRpcResponse(), oversim::Chord::handleRpcResponse(), Broose::handleRpcResponse(), BootstrapList::handleRpcResponse(), PubSubMMOG::handleRpcTimeout(), PubSubLobby::handleRpcTimeout(), NTree::handleRpcTimeout(), oversim::Koorde::handleRpcTimeout(), Kademlia::handleRpcTimeout(), oversim::Chord::handleRpcTimeout(), Broose::handleRpcTimeout(), Pastry::handleStateMessage(), Bamboo::handleStateMessage(), Scribe::handleTimerEvent(), Pastry::handleTimerEvent(), DHTTestApp::handleTimerEvent(), DHT::handleTimerEvent(), CBRDHT::handleTimerEvent(), Bamboo::handleTimerEvent(), Vast::handleUDPMessage(), Quon::handleUDPMessage(), Pastry::handleUDPMessage(), Bamboo::handleUDPMessage(), Scribe::handleUpperMessage(), SimpleGameClient::initializeApp(), BaseRpc::internalHandleRpcMessage(), BaseOverlay::internalHandleRpcTimeout(), Kademlia::isSiblingFor(), NTree::leaveGroup(), MessageObserver::leftGroup(), IterativeLookup::lookup(), SendToKeyListener::lookupFinished(), BaseOverlay::lookupRpc(), Pastry::mergeState(), BasePastry::newLeafs(), operator<<(), BrooseBucket::output(), P2pns::p2pnsRegisterRpc(), BasePastry::pingNodes(), Pastry::pingResponse(), oversim::Chord::pingResponse(), BasePastry::pingResponse(), oversim::Chord::pingTimeout(), BasePastry::pingTimeout(), BasePastry::proxCallback(), Quon::purgeSites(), MessageObserver::receivedMessage(), BaseOverlay::route(), NTree::routeViaNTree(), Vast::sendDiscardNode(), Vast::sendMessage(), Quon::sendMessage(), NTree::sendMessage(), BaseOverlay::sendMessageToUDP(), BaseApp::sendMessageToUDP(), IterativePathLookup::sendRpc(), BasePastry::sendStateTables(), Vast::sendToApp(), Quon::sendToApp(), NTree::sendToGroup(), BaseOverlay::sendToKey(), MessageObserver::sentMessage(), PubSubMMOG::startTimer(), IterativeLookup::stop(), Scribe::subscribeToGroup(), test(), DHT::update(), NeighborCache::updateNcsInfo(), NeighborCache::updateNode(), and Quon::updateThisSite().

{
    if ((base != 2) && (base != 16)) {
        throw cRuntimeError("OverlayKey::OverlayKey(): Invalid base!");
    }

    if (isUnspec)
        return std::string("<unspec>");
    else {
        char temp[MAX_KEYLENGTH+1];

        if (base==16) {
            int k=0;
            for (int i=(keyLength-1)/4; i>=0; i--, k++)
                temp[k] = HEX[this->getBitRange
                              (4*i,4)];

            temp[k] = 0;
            return std::string((const char*)temp);
        } else if (base==2) {
            int k=0;
            for (int i=keyLength-1; i>=0; i-=1, k++)
                temp[k] = HEX[this->getBit(i)];
            temp[k] = 0;
            return std::string((const char*)temp);
        } else {
            throw cRuntimeError("OverlayKey::OverlayKey(): Invalid base!");
        }

// the following native libgmp code doesn't work with leading zeros
#if 0
        mp_size_t last = mpn_get_str((unsigned char*)temp, base,
                                     (mp_limb_t*)this->key, aSize);
        for (int i=0; i<last; i++) {
            temp[i] = HEX[temp[i]];
        }
        temp[last] = 0;
        return std::string((const char*)temp);
#endif

    }
}

void OverlayKey::trim (  )  [inline, private]

trims key after key operations

Definition at line 799 of file OverlayKey.cc.

Referenced by getMax(), operator+=(), operator-=(), operator<<(), operator>>(), operator~(), OverlayKey(), random(), randomPrefix(), randomSuffix(), and sha1().

{
    key[aSize-1] &= GMP_MSB_MASK;
}


Friends And Related Function Documentation

std::ostream& operator<< ( std::ostream &  os,
const OverlayKey c 
) [friend]

Common stdc++ console output method.

Definition at line 618 of file OverlayKey.cc.

{
    os << c.toString(16);
    return os;
};


Member Data Documentation

uint32_t OverlayKey::aSize [static, private]
Initial value:
 OverlayKey::keyLength / (8*sizeof(mp_limb_t)) +
    (OverlayKey::keyLength % (8*sizeof(mp_limb_t))
     != 0 ? 1 : 0)

number of needed machine words to hold the key

Definition at line 482 of file OverlayKey.h.

Referenced by clear(), compareTo(), getMax(), log_2(), operator&(), operator+=(), operator-=(), operator<<(), operator=(), operator>>(), operator^(), operator|(), operator~(), OverlayKey(), random(), randomPrefix(), setKeyLength(), sha1(), sharedPrefixLength(), toString(), and trim().

mp_limb_t OverlayKey::GMP_MSB_MASK [static, private]
Initial value:
 (OverlayKey::keyLength % GMP_LIMB_BITS)
    != 0 ? (((mp_limb_t)1 << (OverlayKey::keyLength % GMP_LIMB_BITS))-1)
    : (mp_limb_t) - 1

bits to fill up if key does not exactly fit in one or more machine words

Definition at line 483 of file OverlayKey.h.

Referenced by setKeyLength(), and trim().

uint32_t OverlayKey::keyLength = MAX_KEYLENGTH [static, private]

actual length of the key

Definition at line 481 of file OverlayKey.h.

Referenced by getBitRange(), getLength(), pow2(), setBit(), setKeyLength(), sharedPrefixLength(), and toString().

const uint32_t OverlayKey::MAX_KEYLENGTH = 160 [static, private]

maximum length of the key

Definition at line 480 of file OverlayKey.h.

Referenced by netPack(), netUnpack(), setKeyLength(), and toString().

const OverlayKey OverlayKey::ZERO [static]

OverlayKey with key initialized as 0.

Definition at line 54 of file OverlayKey.h.

Referenced by operator<<(), operator>>(), pow2(), random(), and test().


The documentation for this class was generated from the following files: