implementation understanding of consistent hashing
1 namespace2 {3 4 classstringifyexception5 {6 };7 8Template <classT>9STD::stringStringify (Constt&t)Ten { One std::ostringstream os; A if(! (OS <<t)) - { - Throwstringifyexception (); the } - returnos.str (); - } - +Template <> -STD::stringStringify (ConstSTD::string&str) + { A returnstr; at } - -Template <> -STD::stringStringify (Const Char*Const&str) - { - returnstr; in } - } to + namespaceconsistent - { the * classemptyringexception $ {Panax Notoginseng }; - theTemplate <classNode,classData,classHash = hash_namespace::hash<Const Char*> > + classhashring A { the Public: +typedef std::map<size_t, Node>Nodemap; - $Hashring (unsignedintreplicas) $: Replicas_ (Replicas), Hash_ (hash_namespace::hash<Const Char*>()) - { - } the -Hashring (unsignedintReplicas,Consthash&hash)Wuyi : Replicas_ (Replicas), hash_ (hash) the { - } Wu -size_t AddNode (Constnode&node); About voidRemoveNode (Constnode&node); $ Constnode& GetNode (Constdata& data)Const; - - Private: - Nodemap Ring_; A ConstUnsignedintReplicas_; + Hash Hash_; the }; - $Template <classNode,classData,classHash> thesize_t Hashring<node, Data, Hash>::addnode (Constnode&node) the { the size_t Hash; theSTD::stringNodestr =stringify (node); - for(unsignedintR =0; R < Replicas_; r++) in { thehash = Hash_ ((nodestr +stringify (R)). C_STR ()); theRing_[hash] =node; About } the returnHash; the } the +Template <classNode,classData,classHash> - voidHashring<node, Data, Hash>::removenode (Constnode&node) the {BayiSTD::stringNodestr =stringify (node); the for(unsignedintR =0; R < Replicas_; r++) the { -size_t hash = hash_ (Nodestr +stringify (R)). C_STR ()); - ring_.erase (hash); the } the } the theTemplate <classNode,classData,classHash> - Constnode& Hashring<node, Data, Hash>::getnode (Constdata& data)Const the { the if(Ring_.empty ()) the Throwemptyringexception ();94 thesize_t hash =Hash_ (stringify (data). C_STR ()); the TypeName Nodemap::const_iterator it; the //Look for the first node >= hash98it =Ring_.lower_bound (hash); About if(It = =ring_.end ()) - {101 //wrapped around; get the first node102it =Ring_.begin ();103 }104 returnIt->second; the }106}
Consistent::hashring, consistent hash.