rbtree.h 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838
  1. // Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef _RBTREE_H
  15. #define _RBTREE_H 1
  16. //! \file datasrc/rbtree.h
  17. ///
  18. /// \note The purpose of the RBTree is to provide a generic map with
  19. /// domain names as the key that can be used by various BIND 10 modules or
  20. /// even by other applications. However, because of some unresolved design
  21. /// issue, the design and interface are not fixed, and RBTree isn't ready
  22. /// to be used as a base data structure by other modules.
  23. #include <exceptions/exceptions.h>
  24. #include <util/memory_segment.h>
  25. #include <dns/name.h>
  26. #include <dns/labelsequence.h>
  27. #include <boost/utility.hpp>
  28. #include <boost/shared_ptr.hpp>
  29. #include <boost/interprocess/offset_ptr.hpp>
  30. #include <boost/static_assert.hpp>
  31. #include <ostream>
  32. #include <algorithm>
  33. #include <cassert>
  34. namespace isc {
  35. namespace datasrc {
  36. /// Forward declare RBTree class here is convinent for following friend
  37. /// class declare inside RBNode and RBTreeNodeChain
  38. template <typename T>
  39. class RBTree;
  40. /// \brief \c RBNode is used by RBTree to store any data related to one domain
  41. /// name.
  42. ///
  43. /// This is meant to be used only from RBTree. It is meaningless to inherit it
  44. /// or create instances of it from elsewhere. For that reason, the constructor
  45. /// (and the allocator, see below) is private.
  46. ///
  47. /// It serves three roles. One is to keep structure of the \c RBTree as a
  48. /// red-black tree. For that purpose, it has left, right and parent pointers
  49. /// and color member. These are private and accessed only from within the tree.
  50. ///
  51. /// The second one is to store data for one domain name. The data related
  52. /// functions can be used to access and set the data.
  53. ///
  54. /// The third role is to keep the hierarchy of domains. The down pointer points
  55. /// to a subtree of subdomains. Note that we can traverse the hierarchy down,
  56. /// but not up.
  57. ///
  58. /// One special kind of node is non-terminal node. It has subdomains with
  59. /// RRsets, but doesn't have any RRsets itself.
  60. ///
  61. /// In order to keep memory footprint as small as possible, the node data
  62. /// are heavily packed. Specifically, some internal node properties (such as
  63. /// the node color) are encoded as part of "flags", some of the flag bits
  64. /// can also be set by the user application. Each node is associated with
  65. /// a sequence of domain name labels, which is essentially the search/insert
  66. /// key for the node (see also the description of RBTree). This is encoded
  67. /// as opaque binary immediately following the main node object. The size
  68. /// of the allocated space for the labels data is encoded by borrowing some
  69. /// bits of the "flags" field.
  70. template <typename T>
  71. class RBNode : public boost::noncopyable {
  72. private:
  73. /// The RBNode is meant for use from within RBTree, so it has access to
  74. /// it.
  75. friend class RBTree<T>;
  76. /// \brief Just a type alias
  77. ///
  78. /// We are going to use a lot of these offset pointers here and they
  79. /// have a long name.
  80. typedef boost::interprocess::offset_ptr<RBNode<T> > RBNodePtr;
  81. /// \name Constructors
  82. ///
  83. /// \note The existence of a RBNode without a RBTree is meaningless.
  84. /// Therefore the constructors are private.
  85. //@{
  86. /// \brief Default constructor.
  87. ///
  88. /// This constructor is provided specifically for generating a special
  89. /// "null" node.
  90. RBNode();
  91. /// \brief Constructor from normal nodes.
  92. RBNode(size_t labels_capacity);
  93. /// \brief Destructor
  94. ~RBNode();
  95. //@}
  96. /// \brief Accessor to the memory region for node labels.
  97. ///
  98. /// The only valid usage of the returned pointer is to pass it to the
  99. /// corresponding constructor of \c dns::LabelSequence.
  100. const void* getLabelsData() const { return (this + 1); }
  101. /// \brief Accessor to the memory region for node labels, mutable version.
  102. ///
  103. /// The only valid usage of the returned pointer is to pass it to
  104. /// \c LabelSequence::serialize() with the node's labels_capacity_ member
  105. /// (which should be sufficiently large for the \c LabelSequence in that
  106. /// context).
  107. void* getLabelsData() { return (this + 1); }
  108. /// \brief Allocate and construct \c RBNode
  109. ///
  110. /// This static method allocates memory for a new \c RBNode object
  111. /// from the given memory segment, constructs the object, and returns
  112. /// a pointer to it.
  113. ///
  114. /// \throw std::bad_alloc Memory allocation fails.
  115. ///
  116. /// \param mem_sgmt A \c MemorySegment from which memory for the new
  117. /// \c RBNode is allocated.
  118. static RBNode<T>* create(util::MemorySegment& mem_sgmt,
  119. const dns::LabelSequence& labels)
  120. {
  121. const size_t labels_len = labels.getSerializedLength();
  122. void* p = mem_sgmt.allocate(sizeof(RBNode<T>) + labels_len);
  123. RBNode<T>* node = new(p) RBNode<T>(labels_len);
  124. labels.serialize(node->getLabelsData(), labels_len);
  125. return (node);
  126. }
  127. /// \brief Destruct and deallocate \c RBNode
  128. ///
  129. /// \throw none
  130. ///
  131. /// \param mem_sgmt The \c MemorySegment that allocated memory for
  132. /// \c rbnode.
  133. /// \param rbnode A non NULL pointer to a valid \c RBNode object
  134. /// that was originally created by the \c create() method (the behavior
  135. /// is undefined if this condition isn't met).
  136. static void destroy(util::MemorySegment& mem_sgmt, RBNode<T>* rbnode) {
  137. const size_t labels_capacity = rbnode->labels_capacity_;
  138. rbnode->~RBNode<T>();
  139. mem_sgmt.deallocate(rbnode, sizeof(RBNode<T>) + labels_capacity);
  140. }
  141. /// \brief Reset node's label sequence to a new one.
  142. ///
  143. /// The new labels must be a sub sequence of the current label sequence;
  144. /// otherwise the serialize() method will throw an exception.
  145. void resetLabels(const dns::LabelSequence& labels) {
  146. labels.serialize(getLabelsData(), labels_capacity_);
  147. }
  148. public:
  149. /// \brief Alias for shared pointer to the data.
  150. typedef boost::shared_ptr<T> NodeDataPtr;
  151. /// Node flags.
  152. ///
  153. /// Each flag value defines a non default property for a specific node.
  154. /// These are defined as bitmask type values for the convenience of
  155. /// internal implementation, but applications are expected to use
  156. /// each flag separately via the enum definitions.
  157. ///
  158. /// All (settable) flags are off by default; they must be explicitly
  159. /// set to on by the \c setFlag() method.
  160. enum Flags {
  161. FLAG_CALLBACK = 1, ///< Callback enabled. See \ref callback
  162. FLAG_RED = 2, ///< Node color; 1 if node is red, 0 if node is black.
  163. FLAG_SUBTREE_ROOT = 4, ///< Set if the node is the root of a subtree
  164. FLAG_USER1 = 0x400000U, ///< Application specific flag
  165. FLAG_USER2 = 0x200000U, ///< Application specific flag
  166. FLAG_USER3 = 0x100000U, ///< Application specific flag
  167. FLAG_MAX = 0x400000U // for integrity check
  168. };
  169. private:
  170. // Some flag values are expected to be used for internal purposes
  171. // (e.g., representing the node color) in future versions, so we
  172. // limit the settable flags via the \c setFlag() method to those
  173. // explicitly defined in \c Flags. This constant represents all
  174. // such flags.
  175. static const uint32_t SETTABLE_FLAGS = (FLAG_CALLBACK | FLAG_USER1 |
  176. FLAG_USER2 | FLAG_USER3);
  177. public:
  178. /// \name Getter functions.
  179. //@{
  180. /// \brief Return the name of current node.
  181. ///
  182. /// It's relative to its containing node.
  183. ///
  184. /// To get the absolute name of one node, the node path from the top node
  185. /// to current node has to be recorded.
  186. const isc::dns::Name getName() const {
  187. assert(labels_capacity_ != 0); // shouldn't be called on a NULL node.
  188. return (dns::Name(dns::LabelSequence(getLabelsData()).toText()));
  189. }
  190. /// \brief Return the label sequence of the node.
  191. ///
  192. /// This method returns the label sequence corresponding to this node
  193. /// in the form of \c dns::LabelSequence object. Any modification to
  194. /// the tree can invalidate the returned \c LabelSequence object or copy
  195. /// of it; in general, it's expected to be used in a very limited scope.
  196. dns::LabelSequence getLabels() const {
  197. assert(labels_capacity_ != 0); // shouldn't be called on a NULL node.
  198. return (dns::LabelSequence(getLabelsData()));
  199. }
  200. /// \brief Return the data stored in this node.
  201. ///
  202. /// You should not delete the data, it is handled by shared pointers.
  203. NodeDataPtr& getData() { return (data_); }
  204. /// \brief Return the data stored in this node.
  205. const NodeDataPtr& getData() const { return (data_); }
  206. /// \brief return whether the node has related data.
  207. ///
  208. /// There can be empty nodes inside the RBTree. They are usually the
  209. /// non-terminal domains, but it is possible (yet probably meaningless)
  210. /// empty nodes anywhere.
  211. bool isEmpty() const { return (data_.get() == NULL); }
  212. //@}
  213. /// \name Setter functions.
  214. //@{
  215. /// \brief Set the data stored in the node.
  216. void setData(const NodeDataPtr& data) { data_ = data; }
  217. //@}
  218. /// \name Node flag manipulation methods
  219. //@{
  220. /// Get the status of a node flag.
  221. ///
  222. /// This method returns whether the given node flag is set (enabled)
  223. /// on the node. The \c flag parameter is expected to be one of the
  224. /// defined \c Flags constants. For simplicity, the method interface
  225. /// does not prohibit passing an undefined flag or combined flags, but
  226. /// the return value in such a case will be meaningless for the caller
  227. /// (an application would have to use an ugly cast for such an unintended
  228. /// form of call, which will hopefully avoid accidental misuse).
  229. ///
  230. /// \exception None
  231. /// \param flag The flag to be tested.
  232. /// \return \c true if the \c flag is set; \c false otherwise.
  233. bool getFlag(Flags flag) const {
  234. return ((flags_ & flag) != 0);
  235. }
  236. /// Set or clear a node flag.
  237. ///
  238. /// This method changes the status of the specified node flag to either
  239. /// "on" (enabled) or "off" (disabled). The new status is specified by
  240. /// the \c on parameter.
  241. /// Like the \c getFlag() method, \c flag is expected to be one of the
  242. /// defined \c Flags constants. If an undefined or unsettable flag is
  243. /// specified, \c isc::InvalidParameter exception will be thrown.
  244. ///
  245. /// \exception isc::InvalidParameter Unsettable flag is specified
  246. /// \exception None otherwise
  247. /// \param flag The node flag to be changed.
  248. /// \param on If \c true, set the flag to on; otherwise set it to off.
  249. void setFlag(Flags flag, bool on = true) {
  250. if ((flag & ~SETTABLE_FLAGS) != 0) {
  251. isc_throw(isc::InvalidParameter,
  252. "Unsettable RBTree flag is being set");
  253. }
  254. if (on) {
  255. flags_ |= flag;
  256. } else {
  257. flags_ &= ~flag;
  258. }
  259. }
  260. //@}
  261. private:
  262. /// \name Callback related methods
  263. ///
  264. /// See the description of \c RBTree<T>::find() at \ref callback
  265. /// about callbacks.
  266. ///
  267. /// These methods never throw an exception.
  268. //@{
  269. /// Return if callback is enabled at the node.
  270. //@}
  271. /// \brief Define rbnode color
  272. enum RBNodeColor {BLACK, RED};
  273. /// This is a factory class method of a special singleton null node.
  274. static RBNode<T>* NULL_NODE() {
  275. static RBNode<T> null_node;
  276. return (&null_node);
  277. }
  278. /// \brief Returns the color of this node
  279. RBNodeColor getColor() const {
  280. if ((flags_ & FLAG_RED) != 0) {
  281. return (RED);
  282. } else {
  283. return (BLACK);
  284. }
  285. }
  286. /// \brief Sets the color of this node
  287. void setColor(const RBNodeColor color) {
  288. if (color == RED) {
  289. flags_ |= FLAG_RED;
  290. } else {
  291. flags_ &= ~FLAG_RED;
  292. }
  293. }
  294. void setSubTreeRoot(bool root) {
  295. if (root) {
  296. flags_ |= FLAG_SUBTREE_ROOT;
  297. } else {
  298. flags_ &= ~FLAG_SUBTREE_ROOT;
  299. }
  300. }
  301. bool isSubTreeRoot() const {
  302. return ((flags_ & FLAG_SUBTREE_ROOT) != 0);
  303. }
  304. /// \brief return the next node which is bigger than current node
  305. /// in the same subtree
  306. ///
  307. /// The next successor for this node is the next bigger node in terms of
  308. /// the DNSSEC order relation within the same single subtree.
  309. /// Note that it may NOT be the next bigger node in the entire RBTree;
  310. /// RBTree is a tree in tree, and the real next node may reside in
  311. /// an upper or lower subtree of the subtree where this node belongs.
  312. /// For example, if this node has a sub domain, the real next node is
  313. /// the smallest node in the sub domain tree.
  314. ///
  315. /// If this node is the biggest node within the subtree, this method
  316. /// returns \c NULL_NODE().
  317. ///
  318. /// This method never throws an exception.
  319. const RBNode<T>* successor() const;
  320. /// \brief return the next node which is smaller than current node
  321. /// in the same subtree
  322. ///
  323. /// The predecessor for this node is the next smaller node in terms of
  324. /// the DNSSEC order relation within the same single subtree.
  325. /// Note that it may NOT be the next smaller node in the entire RBTree;
  326. /// RBTree is a tree in tree, and the real next node may reside in
  327. /// an upper or lower subtree of the subtree where this node belongs.
  328. /// For example, if the predecessor node has a sub domain, the real next
  329. /// node is the largest node in the sub domain tree.
  330. ///
  331. /// If this node is the smallest node within the subtree, this method
  332. /// returns \c NULL_NODE().
  333. ///
  334. /// This method never throws an exception.
  335. const RBNode<T>* predecessor() const;
  336. /// \brief private shared implementation of successor and predecessor
  337. ///
  338. /// As the two mentioned functions are merely mirror images of each other,
  339. /// it makes little sense to keep both versions. So this is the body of the
  340. /// functions and we call it with the correct pointers.
  341. ///
  342. /// Not to be called directly, not even by friends.
  343. ///
  344. /// The overhead of the member pointers should be optimised out, as this
  345. /// will probably get completely inlined into predecessor and successor
  346. /// methods.
  347. const RBNode<T>*
  348. abstractSuccessor(typename RBNode<T>::RBNodePtr RBNode<T>::*left,
  349. typename RBNode<T>::RBNodePtr RBNode<T>::*right)
  350. const;
  351. /// \name Data to maintain the rbtree structure.
  352. ///
  353. /// We keep them as offset pointers. This is part of a future plan, when we
  354. /// want to share the image of the tree between multiple processes.
  355. /// However, whenever we have a chance, we switch to bare pointers during
  356. /// the processing. The pointers on stack are never shared and the offset
  357. /// pointers have non-trivial performance impact.
  358. //@{
  359. RBNodePtr parent_;
  360. /// \brief Access the parent_ as bare pointer.
  361. RBNode<T>* getParent() {
  362. return (parent_.get());
  363. }
  364. /// \brief Access the parent_ as bare pointer, const.
  365. const RBNode<T>* getParent() const {
  366. return (parent_.get());
  367. }
  368. RBNodePtr left_;
  369. /// \brief Access the left_ as bare pointer.
  370. RBNode<T>* getLeft() {
  371. return (left_.get());
  372. }
  373. /// \brief Access the left_ as bare pointer, const.
  374. const RBNode<T>* getLeft() const {
  375. return (left_.get());
  376. }
  377. RBNodePtr right_;
  378. /// \brief Access the right_ as bare pointer.
  379. RBNode<T>* getRight() {
  380. return (right_.get());
  381. }
  382. /// \brief Access the right_ as bare pointer, const.
  383. const RBNode<T>* getRight() const {
  384. return (right_.get());
  385. }
  386. //@}
  387. /// \brief Data stored here.
  388. NodeDataPtr data_;
  389. /// \brief The subdomain tree.
  390. ///
  391. /// This points to the root node of trees of subdomains of this domain.
  392. ///
  393. /// \par Adding down pointer to \c RBNode has two purposes:
  394. /// \li Accelerate the search process, with sub domain tree, it splits the
  395. /// big flat tree into several hierarchy trees.
  396. /// \li It saves memory usage as it allows storing only relative names,
  397. /// avoiding storage of the same domain labels multiple times.
  398. RBNodePtr down_;
  399. /// \brief Access the down_ as bare pointer.
  400. RBNode<T>* getDown() {
  401. return (down_.get());
  402. }
  403. /// \brief Access the down_ as bare pointer, const.
  404. const RBNode<T>* getDown() const {
  405. return (down_.get());
  406. }
  407. /// \brief Internal or user-configurable flags of node's properties.
  408. ///
  409. /// See the \c Flags enum for available flags.
  410. ///
  411. /// For memory efficiency reasons, we only use a subset of the 32-bit
  412. /// space, and use the rest to store the allocated size for the node's
  413. /// label sequence data.
  414. uint32_t flags_ : 23; // largest flag being 0x400000
  415. BOOST_STATIC_ASSERT((1 << 23) > FLAG_MAX); // assumption check
  416. const uint32_t labels_capacity_ : 9; // size for labelseq; range is 0..511
  417. // Make sure the reserved space for labels_capacity_ is sufficiently
  418. // large. In effect, we use the knowledge of the implementation of the
  419. // serialization, but we still only use its public interface, and the
  420. // public interface of this class doesn't rely on this assumption.
  421. // So we can change this implementation without affecting its users if
  422. // a future change to LabelSequence breaks this assumption.
  423. BOOST_STATIC_ASSERT((1 << 9) > dns::LabelSequence::MAX_SERIALIZED_LENGTH);
  424. };
  425. // This is only to support NULL nodes.
  426. template <typename T>
  427. RBNode<T>::RBNode() :
  428. parent_(NULL),
  429. left_(NULL),
  430. right_(NULL),
  431. down_(NULL),
  432. flags_(FLAG_SUBTREE_ROOT),
  433. labels_capacity_(0)
  434. {
  435. // Some compilers object to use of "this" in initializer lists.
  436. parent_ = this;
  437. left_ = this;
  438. right_ = this;
  439. down_ = this;
  440. }
  441. template <typename T>
  442. RBNode<T>::RBNode(size_t labels_capacity) :
  443. parent_(NULL_NODE()),
  444. left_(NULL_NODE()),
  445. right_(NULL_NODE()),
  446. down_(NULL_NODE()),
  447. flags_(FLAG_RED | FLAG_SUBTREE_ROOT),
  448. labels_capacity_(labels_capacity)
  449. {
  450. }
  451. template <typename T>
  452. RBNode<T>::~RBNode() {
  453. }
  454. template <typename T>
  455. const RBNode<T>*
  456. RBNode<T>::abstractSuccessor(typename RBNode<T>::RBNodePtr RBNode<T>::*left,
  457. typename RBNode<T>::RBNodePtr RBNode<T>::*right)
  458. const
  459. {
  460. // This function is written as a successor. It becomes predecessor if
  461. // the left and right pointers are swapped. So in case of predecessor,
  462. // the left pointer points to right and vice versa. Don't get confused
  463. // by the idea, just imagine the pointers look into a mirror.
  464. const RBNode<T>* current = this;
  465. // If it has right node, the successor is the left-most node of the right
  466. // subtree.
  467. if ((current->*right).get() != RBNode<T>::NULL_NODE()) {
  468. current = (current->*right).get();
  469. const RBNode<T>* left_n;
  470. while ((left_n = (current->*left).get()) != RBNode<T>::NULL_NODE()) {
  471. current = left_n;
  472. }
  473. return (current);
  474. }
  475. // Otherwise go up until we find the first left branch on our path to
  476. // root. If found, the parent of the branch is the successor.
  477. // Otherwise, we return the null node
  478. const RBNode<T>* parent = current->getParent();
  479. while (parent != RBNode<T>::NULL_NODE() &&
  480. current == (parent->*right).get()) {
  481. current = parent;
  482. parent = parent->getParent();
  483. }
  484. return (parent);
  485. }
  486. template <typename T>
  487. const RBNode<T>*
  488. RBNode<T>::successor() const {
  489. return (abstractSuccessor(&RBNode<T>::left_, &RBNode<T>::right_));
  490. }
  491. template <typename T>
  492. const RBNode<T>*
  493. RBNode<T>::predecessor() const {
  494. // Swap the left and right pointers for the abstractSuccessor
  495. return (abstractSuccessor(&RBNode<T>::right_, &RBNode<T>::left_));
  496. }
  497. /// \brief RBTreeNodeChain stores detailed information of \c RBTree::find()
  498. /// result.
  499. ///
  500. /// - The \c RBNode that was last compared with the search name, and
  501. /// the comparison result at that point in the form of
  502. /// \c isc::dns::NameComparisonResult.
  503. /// - A sequence of nodes that forms a path to the found node.
  504. ///
  505. /// The comparison result can be used to handle some rare cases such as
  506. /// empty node processing.
  507. /// The node sequence keeps track of the nodes to reach any given node from
  508. /// the root of RBTree.
  509. ///
  510. /// Currently, RBNode does not have "up" pointers in them (i.e., back pointers
  511. /// from the root of one level of tree of trees to the node in the parent
  512. /// tree whose down pointer points to that root node) for memory usage
  513. /// reasons, so there is no other way to find the path back to the root from
  514. /// any given RBNode.
  515. ///
  516. /// \note This design may change in future versions. In particular, it's
  517. /// quite likely we want to have that pointer if we want to optimize name
  518. /// compression by exploiting the structure of the zone. If and when that
  519. /// happens we should also revisit the need for the chaining.
  520. /// Also, the class name may not be appropriate now that it contains other
  521. /// information than a node "chain", and the chain itself may even be
  522. /// deprecated. Something like "RBTreeFindContext" may be a better name.
  523. /// This point should be revisited later.
  524. ///
  525. /// RBTreeNodeChain is constructed and manipulated only inside the \c RBTree
  526. /// class.
  527. /// \c RBTree uses it as an inner data structure to iterate over the whole
  528. /// RBTree.
  529. /// This is the reason why manipulation methods such as \c push() and \c pop()
  530. /// are private (and not shown in the doxygen document).
  531. template <typename T>
  532. class RBTreeNodeChain {
  533. /// RBTreeNodeChain is initialized by RBTree, only RBTree has
  534. /// knowledge to manipulate it.
  535. friend class RBTree<T>;
  536. public:
  537. /// \name Constructors and Assignment Operator.
  538. ///
  539. /// \note The copy constructor and the assignment operator are
  540. /// intentionally defined as private, making this class non copyable.
  541. /// This may have to be changed in a future version with newer need.
  542. /// For now we explicitly disable copy to avoid accidental copy happens
  543. /// unintentionally.
  544. //{@
  545. /// The default constructor.
  546. ///
  547. /// \exception None
  548. RBTreeNodeChain() : node_count_(0), last_compared_(NULL),
  549. // XXX: meaningless initial values:
  550. last_comparison_(0, 0,
  551. isc::dns::NameComparisonResult::EQUAL)
  552. {}
  553. private:
  554. RBTreeNodeChain(const RBTreeNodeChain<T>&);
  555. RBTreeNodeChain<T>& operator=(const RBTreeNodeChain<T>&);
  556. //@}
  557. public:
  558. /// Clear the state of the chain.
  559. ///
  560. /// This method re-initializes the internal state of the chain so that
  561. /// it can be reused for subsequent operations.
  562. ///
  563. /// \exception None
  564. void clear() {
  565. node_count_ = 0;
  566. last_compared_ = NULL;
  567. }
  568. /// Return the \c RBNode that was last compared in \c RBTree::find().
  569. ///
  570. /// If this chain has been passed to \c RBTree::find() and there has
  571. /// been name comparison against the search name, the last compared
  572. /// \c RBNode is recorded within the chain. This method returns that
  573. /// node.
  574. /// If \c RBTree::find() hasn't been called with this chain or name
  575. /// comparison hasn't taken place (which is possible if the tree is empty),
  576. /// this method returns \c NULL.
  577. ///
  578. /// \exception None
  579. const RBNode<T>* getLastComparedNode() const {
  580. return (last_compared_);
  581. }
  582. /// Return the result of last name comparison in \c RBTree::find().
  583. ///
  584. /// Like \c getLastComparedNode(), \c RBTree::find() records the result
  585. /// of the last name comparison in the chain. This method returns the
  586. /// result.
  587. /// The return value of this method is only meaningful when comparison
  588. /// has taken place, i.e, when \c getLastComparedNode() would return a
  589. /// non \c NULL value.
  590. ///
  591. /// \exception None
  592. const isc::dns::NameComparisonResult& getLastComparisonResult() const {
  593. return (last_comparison_);
  594. }
  595. /// \brief Return the number of levels stored in the chain.
  596. ///
  597. /// It's equal to the number of nodes in the chain; for an empty
  598. /// chain, 0 will be returned.
  599. ///
  600. /// \exception None
  601. unsigned int getLevelCount() const { return (node_count_); }
  602. /// \brief return the absolute name for the node which this
  603. /// \c RBTreeNodeChain currently refers to.
  604. ///
  605. /// The chain must not be empty.
  606. ///
  607. /// \exception isc::BadValue the chain is empty.
  608. /// \exception std::bad_alloc memory allocation for the new name fails.
  609. isc::dns::Name getAbsoluteName() const {
  610. if (isEmpty()) {
  611. isc_throw(isc::BadValue,
  612. "RBTreeNodeChain::getAbsoluteName is called on an empty "
  613. "chain");
  614. }
  615. const RBNode<T>* top_node = top();
  616. isc::dns::Name absolute_name = top_node->getName();
  617. int node_count = node_count_ - 1;
  618. while (node_count > 0) {
  619. top_node = nodes_[node_count - 1];
  620. absolute_name = absolute_name.concatenate(top_node->getName());
  621. --node_count;
  622. }
  623. return (absolute_name);
  624. }
  625. private:
  626. // the following private functions check invariants about the internal
  627. // state using assert() instead of exception. The state of a chain
  628. // can only be modified by operations within this file, so if any of the
  629. // assumptions fails it means an internal bug.
  630. /// \brief return whether node chain has node in it.
  631. ///
  632. /// \exception None
  633. bool isEmpty() const { return (node_count_ == 0); }
  634. /// \brief return the top node for the node chain
  635. ///
  636. /// RBTreeNodeChain store all the nodes along top node to
  637. /// root node of RBTree
  638. ///
  639. /// \exception None
  640. const RBNode<T>* top() const {
  641. assert(!isEmpty());
  642. return (nodes_[node_count_ - 1]);
  643. }
  644. /// \brief pop the top node from the node chain
  645. ///
  646. /// After pop, up/super node of original top node will be
  647. /// the top node
  648. ///
  649. /// \exception None
  650. void pop() {
  651. assert(!isEmpty());
  652. --node_count_;
  653. }
  654. /// \brief add the node into the node chain
  655. ///
  656. /// If the node chain isn't empty, the node should be
  657. /// the sub domain of the original top node in node chain
  658. /// otherwise the node should be the root node of RBTree.
  659. ///
  660. /// \exception None
  661. void push(const RBNode<T>* node) {
  662. assert(node_count_ < RBT_MAX_LEVEL);
  663. nodes_[node_count_++] = node;
  664. }
  665. private:
  666. // The max label count for one domain name is Name::MAX_LABELS (128).
  667. // Since each node in rbtree stores at least one label, it's also equal
  668. // to the possible maximum level.
  669. const static int RBT_MAX_LEVEL = isc::dns::Name::MAX_LABELS;
  670. int node_count_;
  671. const RBNode<T>* nodes_[RBT_MAX_LEVEL];
  672. const RBNode<T>* last_compared_;
  673. isc::dns::NameComparisonResult last_comparison_;
  674. };
  675. // note: the following class description is documented using multiline comments
  676. // because the verbatim diagram contain a backslash, which could be interpreted
  677. // as escape of newline in singleline comment.
  678. /**
  679. * \brief \c RBTree class represents all the domains with the same suffix.
  680. * It can be used to store the domains in one zone, for example.
  681. *
  682. * RBTree is a generic map from domain names to any kind of data. Internally,
  683. * it uses a red-black tree. However, it isn't one tree containing everything.
  684. * Subdomains are trees, so this structure is recursive - trees inside trees.
  685. * But, from the interface point of view, it is opaque data structure.
  686. *
  687. * \c RBTree splits the domain space into hierarchy red black trees; nodes
  688. * in one tree has the same base name. The benefit of this struct is that:
  689. * - Enhances the query performace compared with one big flat red black tree.
  690. * - Decreases the memory footprint, as it doesn't store the suffix labels
  691. * multiple times.
  692. *
  693. * Depending on different usage, rbtree will support different search policies.
  694. * Whether to return an empty node to end user is one policy among them.
  695. * The default policy is to NOT return an empty node to end user;
  696. * to change the behavior, specify \c true for the constructor parameter
  697. * \c returnEmptyNode.
  698. * \note The search policy only affects the \c find() behavior of RBTree.
  699. * When inserting one name into RBTree, if the node with the name already
  700. * exists in the RBTree and it's an empty node which doesn't have any data,
  701. * the \c insert() method will still return \c ALREADYEXISTS regardless of
  702. * the search policy.
  703. *
  704. * \anchor diagram
  705. *
  706. * with the following names:
  707. * - a
  708. * - b
  709. * - c
  710. * - x.d.e.f
  711. * - z.d.e.f
  712. * - g.h
  713. * - o.w.y.d.e.f
  714. * - p.w.y.d.e.f
  715. * - q.w.y.d.e.f
  716. *
  717. * the tree will look like:
  718. * \verbatim
  719. .
  720. |
  721. b
  722. / \
  723. a d.e.f
  724. /|\
  725. c | g.h
  726. |
  727. w.y
  728. /|\
  729. x | z
  730. |
  731. p
  732. / \
  733. o q
  734. \endverbatim
  735. * \todo
  736. * - add remove interface
  737. */
  738. template <typename T>
  739. class RBTree : public boost::noncopyable {
  740. friend class RBNode<T>;
  741. public:
  742. /// \brief The return value for the \c find() and insert() methods
  743. enum Result {
  744. SUCCESS, ///< Insert was successful
  745. /// \brief The node returned from find mathes exactly the name given
  746. EXACTMATCH,
  747. PARTIALMATCH, ///< A superdomain node was found
  748. NOTFOUND, ///< Not even any superdomain was found
  749. /// \brief Returned by insert() if a node of the name already exists
  750. ALREADYEXISTS,
  751. };
  752. /// \brief Allocate and construct \c RBTree
  753. ///
  754. /// This static method allocates memory for a new \c RBTree object
  755. /// from the given memory segment, constructs the object, and returns
  756. /// a pointer to it.
  757. ///
  758. /// \throw std::bad_alloc Memory allocation fails.
  759. ///
  760. /// \param mem_sgmt A \c MemorySegment from which memory for the new
  761. /// \c RBTree is allocated.
  762. static RBTree* create(util::MemorySegment& mem_sgmt,
  763. bool return_empty_node = false)
  764. {
  765. void* p = mem_sgmt.allocate(sizeof(RBTree<T>));
  766. return (new(p) RBTree<T>(return_empty_node));
  767. }
  768. /// \brief Destruct and deallocate \c RBTree
  769. ///
  770. /// This method also destroys and deallocates all nodes inserted to the
  771. /// tree.
  772. ///
  773. /// \note The memory segment (\c mem_sgmt) must be the same one that
  774. /// was originally used to allocate memory for the tree (and for all
  775. /// nodes inserted to the tree, due to the requirement of \c insert()),
  776. /// since the tree itself doesn't maintain a reference to the segment.
  777. /// This is not a robust interface, but since we plan to share the tree
  778. /// structure by multiple processes via shared memory or possibly allow
  779. /// the memory image to be dumped to a file for later reload, there
  780. /// doesn't seem to be an easy way to store such reference in the data
  781. /// itself. We should probably consider a wrapper interface that
  782. /// encapsulates the corresponding segment and always use it for any
  783. /// allocation/deallocation of tree related data (the tree itself, their
  784. /// nodes, and node data) to keep the usage as safe as possible.
  785. ///
  786. /// \throw none
  787. ///
  788. /// \param mem_sgmt The \c MemorySegment that allocated memory for
  789. /// \c rbtree and for all nodes inserted to the tree.
  790. /// \param rbtree A non NULL pointer to a valid \c RBTree object
  791. /// that was originally created by the \c create() method (the behavior
  792. /// is undefined if this condition isn't met).
  793. static void destroy(util::MemorySegment& mem_sgmt, RBTree<T>* rbtree) {
  794. rbtree->deleteAllNodes(mem_sgmt);
  795. rbtree->~RBTree<T>();
  796. mem_sgmt.deallocate(rbtree, sizeof(RBTree<T>));
  797. }
  798. private:
  799. /// \name Constructor and Destructor
  800. //@{
  801. /// \brief The constructor.
  802. ///
  803. /// An object of this class is always expected to be created by the
  804. /// allocator (\c create()), so the constructor is hidden as private.
  805. ///
  806. /// It never throws an exception.
  807. explicit RBTree(bool returnEmptyNode = false);
  808. /// \brief The destructor.
  809. ///
  810. /// An object of this class is always expected to be destroyed explicitly
  811. /// by \c destroy(), so the constructor is hidden as private.
  812. ///
  813. /// \note RBTree is not intended to be inherited so the destructor
  814. /// is not virtual
  815. ~RBTree();
  816. //@}
  817. public:
  818. /// \name Find methods
  819. ///
  820. /// \brief Find the node that gives a longest match against the given name.
  821. ///
  822. /// \anchor find
  823. ///
  824. /// These methods search the RBTree for a node whose name is longest
  825. /// against name. The found node, if any, is returned via the node pointer.
  826. ///
  827. /// By default, nodes that don't have data (see RBNode::isEmpty) are
  828. /// ignored and the result can be NOTFOUND even if there's a node whose
  829. /// name matches. If the \c RBTree is constructed with its
  830. /// \c returnEmptyNode parameter being \c true, empty nodes will also
  831. /// be match candidates.
  832. ///
  833. /// \note Even when \c returnEmptyNode is \c true, not all empty nodes
  834. /// in terms of the DNS protocol may necessarily be found by this method.
  835. /// For example, in the \ref diagram shown in the class description,
  836. /// the name y.d.e.f is logically contained in the tree as part of the
  837. /// node w.y, but the \c find() variants cannot find the former for
  838. /// the search key of y.d.e.f, no matter how the \c RBTree is constructed.
  839. /// The caller of this method must use a different way to identify the
  840. /// hidden match when necessary.
  841. ///
  842. /// These methods involve operations on names that can throw an exception.
  843. /// If that happens the exception will be propagated to the caller.
  844. /// The callback function should generally not throw an exception, but
  845. /// if it throws, the exception will be propagated to the caller.
  846. ///
  847. /// The \c name parameter says what should be found. The node parameter
  848. /// is output-only, and in case of EXACTMATCH or PARTIALMATCH, it is set
  849. /// to a pointer to the found node.
  850. ///
  851. /// They return:
  852. /// - EXACTMATCH when a node with the same name as requested exists.
  853. /// - PARTIALMATCH when a node with the same name does not exist (or is
  854. /// empty), but there's a (nonempty) superdomain of the requested one.
  855. /// The superdomain with longest name is returned through the node
  856. /// parameter. Beware that if you store a zone in the tree, you may get
  857. /// PARTIALMATCH with zone apex when the given domain name is not there.
  858. /// You should not try to delegate into another zone in that case.
  859. /// - NOTFOUND if there's no node with the same name nor any superdomain
  860. /// of it. In that case, node parameter is left intact.
  861. //@{
  862. /// \brief Simple find.
  863. ///
  864. /// Acts as described in the \ref find section.
  865. Result find(const isc::dns::Name& name, RBNode<T>** node) const {
  866. RBTreeNodeChain<T> node_path;
  867. return (find<void*>(name, node, node_path, NULL, NULL));
  868. }
  869. /// \brief Simple find returning immutable node.
  870. ///
  871. /// Acts as described in the \ref find section, but returns immutable node
  872. /// pointer.
  873. Result find(const isc::dns::Name& name, const RBNode<T>** node) const {
  874. RBTreeNodeChain<T> node_path;
  875. RBNode<T> *target_node = NULL;
  876. Result ret = (find<void*>(name, &target_node, node_path, NULL, NULL));
  877. if (ret != NOTFOUND) {
  878. *node = target_node;
  879. }
  880. return (ret);
  881. }
  882. /// \brief Simple find, with node_path tracking
  883. ///
  884. /// Acts as described in the \ref find section.
  885. Result find(const isc::dns::Name& name, RBNode<T>** node,
  886. RBTreeNodeChain<T>& node_path) const
  887. {
  888. return (find<void*>(name, node, node_path, NULL, NULL));
  889. }
  890. /// \brief Simple find returning immutable node, with node_path tracking
  891. ///
  892. /// Acts as described in the \ref find section, but returns immutable node
  893. /// pointer.
  894. Result find(const isc::dns::Name& name, const RBNode<T>** node,
  895. RBTreeNodeChain<T>& node_path) const
  896. {
  897. RBNode<T> *target_node = NULL;
  898. Result ret = (find<void*>(name, &target_node, node_path, NULL, NULL));
  899. if (ret != NOTFOUND) {
  900. *node = target_node;
  901. }
  902. return (ret);
  903. }
  904. /// \brief Find with callback and node chain.
  905. /// \anchor callback
  906. ///
  907. /// This version of \c find() is specifically designed for the backend
  908. /// of the \c InMemoryZoneFinder class, and implements all necessary
  909. /// features for that purpose. Other applications shouldn't need these
  910. /// additional features, and should normally use the simpler versions.
  911. ///
  912. /// This version of \c find() calls the callback whenever traversing (on
  913. /// the way from root down the tree) a marked node on the way down through
  914. /// the domain namespace (see \c RBNode::FLAG_CALLBACK).
  915. ///
  916. /// If you return true from the callback, the search is stopped and a
  917. /// PARTIALMATCH is returned with the given node. Note that this node
  918. /// doesn't really need to be the one with longest possible match.
  919. ///
  920. /// The callback is not called for the node which matches exactly
  921. /// (EXACTMATCH is returned). This is typically the last node in the
  922. /// traversal during a successful search.
  923. ///
  924. /// This callback mechanism was designed with zone cut (delegation)
  925. /// processing in mind. The marked nodes would be the ones at delegation
  926. /// points. It is not expected that any other applications would need
  927. /// callbacks; they should use the versions of find without callbacks.
  928. /// The callbacks are not general functors for the same reason - we don't
  929. /// expect it to be needed.
  930. ///
  931. /// Another special feature of this version is the ability to record
  932. /// more detailed information regarding the search result.
  933. ///
  934. /// This information will be returned via the \c node_path parameter,
  935. /// which is an object of class \c RBTreeNodeChain.
  936. /// The passed parameter must be empty.
  937. ///
  938. /// On success, the node sequence stored in \c node_path will contain all
  939. /// the ancestor nodes from the found node towards the root.
  940. /// For example, if we look for o.w.y.d.e.f in the example \ref diagram,
  941. /// \c node_path will contain w.y and d.e.f; the \c top() node of the
  942. /// chain will be o, w.y and d.e.f will be stored below it.
  943. ///
  944. /// This feature can be used to get the absolute name for a node;
  945. /// to do so, we need to travel upside from the node toward the root,
  946. /// concatenating all ancestor names. With the current implementation
  947. /// it's not possible without a node chain, because there is a no pointer
  948. /// from the root of a subtree to the parent subtree (this may change
  949. /// in a future version). A node chain can also be used to find the
  950. /// next and previous nodes of a given node in the entire RBTree;
  951. /// the \c nextNode() and \c previousNode() methods take a node
  952. /// chain as a parameter.
  953. ///
  954. /// \exception isc::BadValue node_path is not empty.
  955. ///
  956. /// \param name Target to be found
  957. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  958. /// it will store a pointer to the matching node
  959. /// \param node_path Other search details will be stored (see the
  960. /// description)
  961. /// \param callback If non- \c NULL, a call back function to be called
  962. /// at marked nodes (see the description).
  963. /// \param callback_arg A caller supplied argument to be passed to
  964. /// \c callback.
  965. ///
  966. /// \return As in the description, but in case of callback returning
  967. /// \c true, it returns immediately with the current node.
  968. template <typename CBARG>
  969. Result find(const isc::dns::Name& name,
  970. RBNode<T>** node,
  971. RBTreeNodeChain<T>& node_path,
  972. bool (*callback)(const RBNode<T>&, CBARG),
  973. CBARG callback_arg) const;
  974. /// \brief Simple find returning immutable node.
  975. ///
  976. /// Acts as described in the \ref find section, but returns immutable
  977. /// node pointer.
  978. template <typename CBARG>
  979. Result find(const isc::dns::Name& name,
  980. const RBNode<T>** node,
  981. RBTreeNodeChain<T>& node_path,
  982. bool (*callback)(const RBNode<T>&, CBARG),
  983. CBARG callback_arg) const
  984. {
  985. RBNode<T>* target_node = NULL;
  986. Result ret = find(name, &target_node, node_path, callback,
  987. callback_arg);
  988. if (ret != NOTFOUND) {
  989. *node = target_node;
  990. }
  991. return (ret);
  992. }
  993. //@}
  994. /// \brief return the next bigger node in DNSSEC order from a given node
  995. /// chain.
  996. ///
  997. /// This method identifies the next bigger node of the node currently
  998. /// referenced in \c node_path and returns it.
  999. /// This method also updates the passed \c node_path so that it will store
  1000. /// the path for the returned next node.
  1001. /// It will be convenient when we want to iterate over the all nodes
  1002. /// of \c RBTree; we can do this by calling this method repeatedly
  1003. /// starting from the root node.
  1004. ///
  1005. /// \note \c nextNode() will iterate over all the nodes in RBTree including
  1006. /// empty nodes. If empty node isn't desired, it's easy to add logic to
  1007. /// check return node and keep invoking \c nextNode() until the non-empty
  1008. /// node is retrieved.
  1009. ///
  1010. /// \exception isc::BadValue node_path is empty.
  1011. ///
  1012. /// \param node_path A node chain that stores all the nodes along the path
  1013. /// from root to node.
  1014. ///
  1015. /// \return An \c RBNode that is next bigger than \c node; if \c node is
  1016. /// the largest, \c NULL will be returned.
  1017. const RBNode<T>* nextNode(RBTreeNodeChain<T>& node_path) const;
  1018. /// \brief return the next smaller node in DNSSEC order from a node
  1019. /// searched by RBTree::find().
  1020. ///
  1021. /// This acts similarly to \c nextNode(), but it walks in the other
  1022. /// direction. But unlike \c nextNode(), this can start even if the
  1023. /// node requested by \c find() was not found. In that case, it will
  1024. /// identify the node that is previous to the queried name.
  1025. ///
  1026. /// \note \c previousNode() will iterate over all the nodes in RBTree
  1027. /// including empty nodes. If empty node isn't desired, it's easy to add
  1028. /// logic to check return node and keep invoking \c previousNode() until the
  1029. /// non-empty node is retrieved.
  1030. ///
  1031. /// \exception isc::BadValue node_path is empty.
  1032. ///
  1033. /// \param node_path A node chain that stores all the nodes along the path
  1034. /// from root to node and the result of \c find(). This will get modified.
  1035. /// You should not use the node_path again except for repetitive calls
  1036. /// of this method.
  1037. ///
  1038. /// \return An \c RBNode that is next smaller than \c node; if \c node is
  1039. /// the smallest, \c NULL will be returned.
  1040. const RBNode<T>* previousNode(RBTreeNodeChain<T>& node_path) const;
  1041. /// \brief Get the total number of nodes in the tree
  1042. ///
  1043. /// It includes nodes internally created as a result of adding a domain
  1044. /// name that is a subdomain of an existing node of the tree.
  1045. /// This function is mainly intended to be used for debugging.
  1046. int getNodeCount() const { return (node_count_); }
  1047. /// \name Debug function
  1048. //@{
  1049. /// \brief Print the nodes in the trees.
  1050. ///
  1051. /// \param os A \c std::ostream object to which the tree is printed.
  1052. /// \param depth A factor of the initial indentation. Each line
  1053. /// will begin with space character repeating <code>5 * depth</code>
  1054. /// times.
  1055. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  1056. //@}
  1057. /// \name Modify functions
  1058. //@{
  1059. /// \brief Insert the domain name into the tree.
  1060. ///
  1061. /// It either finds an already existing node of the given name, or inserts
  1062. /// a new one if none exists yet. In any case, the \c inserted_node parameter
  1063. /// is set to point to that node. You can fill data into it or modify it.
  1064. /// So, if you don't know if a node exists or not and you need to modify
  1065. /// it, just call insert and act by the result.
  1066. ///
  1067. /// Please note that the tree can add some empty nodes by itself, so don't
  1068. /// assume that if you didn't insert a node of that name it doesn't exist.
  1069. ///
  1070. /// This method normally involves resource allocation. If it fails
  1071. /// the corresponding standard exception will be thrown.
  1072. ///
  1073. /// This method does not provide the strong exception guarantee in its
  1074. /// strict sense; if an exception is thrown in the middle of this
  1075. /// method, the internal structure may change. However, it should
  1076. /// still retain the same property as a mapping container before this
  1077. /// method is called. For example, the result of \c find() should be
  1078. /// the same. This method provides the weak exception guarantee in its
  1079. /// normal sense.
  1080. ///
  1081. /// \param mem_sgmt A \c MemorySegment object for allocating memory of
  1082. /// a new node to be inserted. Must be the same segment as that used
  1083. /// for creating the tree itself.
  1084. /// \param name The name to be inserted into the tree.
  1085. /// \param inserted_node This is an output parameter and is set to the
  1086. /// node.
  1087. ///
  1088. /// \return
  1089. /// - SUCCESS The node was added.
  1090. /// - ALREADYEXISTS There was already a node of that name, so it was not
  1091. /// added.
  1092. Result insert(util::MemorySegment& mem_sgmt, const isc::dns::Name& name,
  1093. RBNode<T>** inserted_node);
  1094. /// \brief Delete all tree nodes.
  1095. ///
  1096. /// \throw none.
  1097. ///
  1098. /// \param mem_sgmt The \c MemorySegment object used to insert the nodes
  1099. /// (which was also used for creating the tree due to the requirement of
  1100. /// \c inert()).
  1101. void deleteAllNodes(util::MemorySegment& mem_sgmt);
  1102. /// \brief Swaps two tree's contents.
  1103. ///
  1104. /// This and \c other trees must have been created with the same
  1105. /// memory segment (see the discussion in \c create()); otherwise the
  1106. /// behavior is undefined.
  1107. ///
  1108. /// This acts the same as many std::*.swap functions, exchanges the
  1109. /// contents. This doesn't throw anything.
  1110. void swap(RBTree<T>& other) {
  1111. std::swap(root_, other.root_);
  1112. std::swap(NULLNODE, other.NULLNODE);
  1113. std::swap(node_count_, other.node_count_);
  1114. }
  1115. //@}
  1116. private:
  1117. /// \name RBTree balance functions
  1118. //@{
  1119. void insertRebalance(typename RBNode<T>::RBNodePtr* root, RBNode<T>* node);
  1120. RBNode<T>* rightRotate(typename RBNode<T>::RBNodePtr* root,
  1121. RBNode<T>* node);
  1122. RBNode<T>* leftRotate(typename RBNode<T>::RBNodePtr* root,
  1123. RBNode<T>* node);
  1124. //@}
  1125. /// \name Helper functions
  1126. //@{
  1127. /// \brief delete tree whose root is equal to node
  1128. void deleteHelper(util::MemorySegment& mem_sgmt, RBNode<T> *node);
  1129. /// \brief Print the information of given RBNode.
  1130. void dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  1131. unsigned int depth) const;
  1132. /// \brief Indentation helper function for dumpTree
  1133. static void indent(std::ostream& os, unsigned int depth);
  1134. /// Split one node into two nodes for "prefix" and "suffix" parts of
  1135. /// the labels of the original node, respectively. The given node
  1136. /// will hold the suffix labels, while the new node will hold the prefix.
  1137. /// The newly created node represents the labels that the original node
  1138. /// did, so necessary data are swapped.
  1139. /// (Note: as commented in the code, this behavior should be changed).
  1140. void nodeFission(util::MemorySegment& mem_sgmt, RBNode<T>& node,
  1141. const isc::dns::LabelSequence& new_prefix,
  1142. const isc::dns::LabelSequence& new_suffix);
  1143. //@}
  1144. RBNode<T>* NULLNODE;
  1145. typename RBNode<T>::RBNodePtr root_;
  1146. /// the node count of current tree
  1147. unsigned int node_count_;
  1148. /// search policy for rbtree
  1149. const bool needsReturnEmptyNode_;
  1150. };
  1151. template <typename T>
  1152. RBTree<T>::RBTree(bool returnEmptyNode) :
  1153. NULLNODE(RBNode<T>::NULL_NODE()),
  1154. root_(NULLNODE),
  1155. node_count_(0),
  1156. needsReturnEmptyNode_(returnEmptyNode)
  1157. {
  1158. }
  1159. template <typename T>
  1160. RBTree<T>::~RBTree() {
  1161. assert(node_count_ == 0);
  1162. }
  1163. template <typename T>
  1164. void
  1165. RBTree<T>::deleteHelper(util::MemorySegment& mem_sgmt, RBNode<T>* root) {
  1166. if (root == NULLNODE) {
  1167. return;
  1168. }
  1169. RBNode<T>* node = root;
  1170. while (root->getLeft() != NULLNODE || root->getRight() != NULLNODE) {
  1171. RBNode<T>* left(NULLNODE);
  1172. RBNode<T>* right(NULLNODE);
  1173. while ((left = node->getLeft()) != NULLNODE ||
  1174. (right = node->getRight()) != NULLNODE) {
  1175. node = (left != NULLNODE) ? left : right;
  1176. }
  1177. RBNode<T>* parent = node->getParent();
  1178. if (parent->getLeft() == node) {
  1179. parent->left_ = NULLNODE;
  1180. } else {
  1181. parent->right_ = NULLNODE;
  1182. }
  1183. deleteHelper(mem_sgmt, node->getDown());
  1184. RBNode<T>::destroy(mem_sgmt, node);
  1185. --node_count_;
  1186. node = parent;
  1187. }
  1188. deleteHelper(mem_sgmt, root->getDown());
  1189. RBNode<T>::destroy(mem_sgmt, root);
  1190. --node_count_;
  1191. }
  1192. template <typename T>
  1193. template <typename CBARG>
  1194. typename RBTree<T>::Result
  1195. RBTree<T>::find(const isc::dns::Name& target_name,
  1196. RBNode<T>** target,
  1197. RBTreeNodeChain<T>& node_path,
  1198. bool (*callback)(const RBNode<T>&, CBARG),
  1199. CBARG callback_arg) const
  1200. {
  1201. if (!node_path.isEmpty()) {
  1202. isc_throw(isc::BadValue, "RBTree::find is given a non empty chain");
  1203. }
  1204. RBNode<T>* node = root_.get();
  1205. Result ret = NOTFOUND;
  1206. dns::LabelSequence target_labels(target_name);
  1207. while (node != NULLNODE) {
  1208. node_path.last_compared_ = node;
  1209. node_path.last_comparison_ = target_labels.compare(node->getLabels());
  1210. const isc::dns::NameComparisonResult::NameRelation relation =
  1211. node_path.last_comparison_.getRelation();
  1212. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1213. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1214. node_path.push(node);
  1215. *target = node;
  1216. ret = EXACTMATCH;
  1217. }
  1218. break;
  1219. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1220. // If the two labels have no hierarchical relationship in terms
  1221. // of matching, we should continue the binary search.
  1222. node = (node_path.last_comparison_.getOrder() < 0) ?
  1223. node->getLeft() : node->getRight();
  1224. } else {
  1225. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1226. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1227. ret = PARTIALMATCH;
  1228. *target = node;
  1229. if (callback != NULL &&
  1230. node->getFlag(RBNode<T>::FLAG_CALLBACK)) {
  1231. if ((callback)(*node, callback_arg)) {
  1232. break;
  1233. }
  1234. }
  1235. }
  1236. node_path.push(node);
  1237. target_labels.stripRight(
  1238. node_path.last_comparison_.getCommonLabels());
  1239. node = node->getDown();
  1240. } else {
  1241. break;
  1242. }
  1243. }
  1244. }
  1245. return (ret);
  1246. }
  1247. template <typename T>
  1248. const RBNode<T>*
  1249. RBTree<T>::nextNode(RBTreeNodeChain<T>& node_path) const {
  1250. if (node_path.isEmpty()) {
  1251. isc_throw(isc::BadValue, "RBTree::nextNode is given an empty chain");
  1252. }
  1253. const RBNode<T>* node = node_path.top();
  1254. // if node has sub domain, the next domain is the smallest
  1255. // domain in sub domain tree
  1256. const RBNode<T>* down = node->getDown();
  1257. if (down != NULLNODE) {
  1258. const RBNode<T>* left_most = down;
  1259. while (left_most->getLeft() != NULLNODE) {
  1260. left_most = left_most->getLeft();
  1261. }
  1262. node_path.push(left_most);
  1263. return (left_most);
  1264. }
  1265. // try to find a successor.
  1266. // if no successor found move to up level, the next successor
  1267. // is the successor of up node in the up level tree, if
  1268. // up node doesn't have successor we gonna keep moving to up
  1269. // level
  1270. while (!node_path.isEmpty()) {
  1271. const RBNode<T>* up_node_successor = node_path.top()->successor();
  1272. node_path.pop();
  1273. if (up_node_successor != NULLNODE) {
  1274. node_path.push(up_node_successor);
  1275. return (up_node_successor);
  1276. }
  1277. }
  1278. return (NULL);
  1279. }
  1280. template <typename T>
  1281. const RBNode<T>*
  1282. RBTree<T>::previousNode(RBTreeNodeChain<T>& node_path) const {
  1283. if (getNodeCount() == 0) {
  1284. // Special case for empty trees. It would look every time like
  1285. // we didn't search, because the last compared is empty. This is
  1286. // a slight hack and not perfect, but this is better than throwing
  1287. // on empty tree. And we probably won't meet an empty tree in practice
  1288. // anyway.
  1289. return (NULL);
  1290. }
  1291. if (node_path.last_compared_ == NULL) {
  1292. isc_throw(isc::BadValue,
  1293. "RBTree::previousNode() called before find()");
  1294. }
  1295. // If the relation isn't EQUAL, it means the find was called previously
  1296. // and didn't find the exact node. Therefore we need to locate the place
  1297. // to start iterating the chain of domains.
  1298. //
  1299. // The logic here is not too complex, we just need to take care to handle
  1300. // all the cases and decide where to go from there.
  1301. switch (node_path.last_comparison_.getRelation()) {
  1302. case dns::NameComparisonResult::COMMONANCESTOR:
  1303. case dns::NameComparisonResult::NONE:
  1304. // We compared with a leaf in the tree and wanted to go to one of
  1305. // the children. But the child was not there. It now depends on the
  1306. // direction in which we wanted to go.
  1307. if (node_path.last_comparison_.getOrder() < 0) {
  1308. // We wanted to go left. So the one we compared with is
  1309. // the one higher than we wanted. If we just put it into
  1310. // the node_path, then the following algorithm below will find
  1311. // the smaller one.
  1312. //
  1313. // This is exactly the same as with superdomain below.
  1314. // Therefore, we just fall through to the next case.
  1315. } else {
  1316. // We wanted to go right. That means we want to output the
  1317. // one which is the largest in the tree defined by the
  1318. // compared one (it is either the compared one, or some
  1319. // subdomain of it). There probably is not an easy trick
  1320. // for this, so we just find the correct place.
  1321. const RBNode<T>* current(node_path.last_compared_);
  1322. while (current != NULLNODE) {
  1323. node_path.push(current);
  1324. // Go a level down and as much right there as possible
  1325. current = current->getDown();
  1326. const RBNode<T>* right(NULLNODE);
  1327. while ((right = current->getRight()) != NULLNODE) {
  1328. // A small trick. The current may be NULLNODE, but
  1329. // such node has the right_ pointer and it is equal
  1330. // to NULLNODE.
  1331. current = right;
  1332. }
  1333. }
  1334. // Now, the one on top of the path is the one we want. We
  1335. // return it now and leave it there, so we can search for
  1336. // previous of it the next time we'are called.
  1337. node_path.last_comparison_ =
  1338. dns::NameComparisonResult(0, 0,
  1339. dns::NameComparisonResult::EQUAL);
  1340. return (node_path.top());
  1341. }
  1342. // No break; here - we want to fall through. See above.
  1343. case dns::NameComparisonResult::SUPERDOMAIN:
  1344. // This is the case there's a "compressed" node and we looked for
  1345. // only part of it. The node itself is larger than we wanted, but
  1346. // if we put it to the node_path and then go one step left from it,
  1347. // we get the correct result.
  1348. node_path.push(node_path.last_compared_);
  1349. // Correct the comparison result, so we won't trigger this case
  1350. // next time previousNode is called. We already located the correct
  1351. // place to start. The value is partly nonsense, but that doesn't
  1352. // matter any more.
  1353. node_path.last_comparison_ =
  1354. dns::NameComparisonResult(0, 0,
  1355. dns::NameComparisonResult::EQUAL);
  1356. break;
  1357. case dns::NameComparisonResult::SUBDOMAIN:
  1358. // A subdomain means we returned the one above the searched one
  1359. // already and it is on top of the stack. This is was smaller
  1360. // than the one already, but we want to return yet smaller one.
  1361. // So we act as if it was EQUAL.
  1362. break;
  1363. case dns::NameComparisonResult::EQUAL:
  1364. // The find gave us an exact match or the previousNode was called
  1365. // already, which located the exact node. The rest of the function
  1366. // goes one domain left and returns it for us.
  1367. break;
  1368. }
  1369. // So, the node_path now contains the path to a node we want previous for.
  1370. // We just need to go one step left.
  1371. if (node_path.isEmpty()) {
  1372. // We got past the first one. So, we're returning NULL from
  1373. // now on.
  1374. return (NULL);
  1375. }
  1376. const RBNode<T>* node(node_path.top());
  1377. // Try going left in this tree
  1378. node = node->predecessor();
  1379. if (node == NULLNODE) {
  1380. // We are the smallest ones in this tree. We go one level
  1381. // up. That one is the smaller one than us.
  1382. node_path.pop();
  1383. if (node_path.isEmpty()) {
  1384. // We're past the first one
  1385. return (NULL);
  1386. } else {
  1387. return (node_path.top());
  1388. }
  1389. }
  1390. // Exchange the node at the top of the path, as we move horizontaly
  1391. // through the domain tree
  1392. node_path.pop();
  1393. node_path.push(node);
  1394. // Try going as deep as possible, keeping on the right side of the trees
  1395. const RBNode<T>* down;
  1396. while ((down = node->getDown()) != NULLNODE) {
  1397. // Move to the tree below
  1398. node = down;
  1399. // And get as much to the right of the tree as possible
  1400. const RBNode<T>* right(NULLNODE);
  1401. while ((right = node->getRight()) != NULLNODE) {
  1402. node = right;
  1403. }
  1404. // Now, we found the right-most node in the sub-tree, we need to
  1405. // include it in the path
  1406. node_path.push(node);
  1407. }
  1408. // Now, if the current node has no down_ pointer any more, it's the
  1409. // correct one.
  1410. return (node);
  1411. }
  1412. template <typename T>
  1413. typename RBTree<T>::Result
  1414. RBTree<T>::insert(util::MemorySegment& mem_sgmt,
  1415. const isc::dns::Name& target_name, RBNode<T>** new_node)
  1416. {
  1417. RBNode<T>* parent = NULLNODE;
  1418. RBNode<T>* current = root_.get();
  1419. RBNode<T>* up_node = NULLNODE;
  1420. isc::dns::LabelSequence target_labels(target_name);
  1421. int order = -1;
  1422. while (current != NULLNODE) {
  1423. const dns::LabelSequence current_labels(current->getLabels());
  1424. const isc::dns::NameComparisonResult compare_result =
  1425. target_labels.compare(current_labels);
  1426. const isc::dns::NameComparisonResult::NameRelation relation =
  1427. compare_result.getRelation();
  1428. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1429. if (new_node != NULL) {
  1430. *new_node = current;
  1431. }
  1432. return (ALREADYEXISTS);
  1433. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1434. parent = current;
  1435. order = compare_result.getOrder();
  1436. current = order < 0 ? current->getLeft() : current->getRight();
  1437. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1438. // insert sub domain to sub tree
  1439. parent = NULLNODE;
  1440. up_node = current;
  1441. target_labels.stripRight(compare_result.getCommonLabels());
  1442. current = current->getDown();
  1443. } else {
  1444. // The number of labels in common is fewer than the number of
  1445. // labels at the current node, so the current node must be
  1446. // adjusted to have just the common suffix, and a down pointer
  1447. // made to a new tree.
  1448. dns::LabelSequence common_ancestor = target_labels;
  1449. common_ancestor.stripLeft(target_labels.getLabelCount() -
  1450. compare_result.getCommonLabels());
  1451. dns::LabelSequence new_prefix = current_labels;
  1452. new_prefix.stripRight(compare_result.getCommonLabels());
  1453. nodeFission(mem_sgmt, *current, new_prefix, common_ancestor);
  1454. }
  1455. }
  1456. typename RBNode<T>::RBNodePtr* current_root = (up_node != NULLNODE) ?
  1457. &(up_node->down_) : &root_;
  1458. // Once a new node is created, no exception will be thrown until the end
  1459. // of the function, so we can simply create and hold a new node pointer.
  1460. RBNode<T>* node = RBNode<T>::create(mem_sgmt, target_labels);
  1461. node->parent_ = parent;
  1462. if (parent == NULLNODE) {
  1463. *current_root = node;
  1464. // node is the new root of sub tree, so its init color is BLACK
  1465. node->setColor(RBNode<T>::BLACK);
  1466. node->setSubTreeRoot(true);
  1467. } else if (order < 0) {
  1468. node->setSubTreeRoot(false);
  1469. parent->left_ = node;
  1470. } else {
  1471. node->setSubTreeRoot(false);
  1472. parent->right_ = node;
  1473. }
  1474. insertRebalance(current_root, node);
  1475. if (new_node != NULL) {
  1476. *new_node = node;
  1477. }
  1478. ++node_count_;
  1479. return (SUCCESS);
  1480. }
  1481. template <typename T>
  1482. void
  1483. RBTree<T>::deleteAllNodes(util::MemorySegment& mem_sgmt) {
  1484. deleteHelper(mem_sgmt, root_.get());
  1485. root_ = NULLNODE;
  1486. }
  1487. // Note: when we redesign this (still keeping the basic concept), we should
  1488. // change this part so the newly created node will be used for the inserted
  1489. // name (and therefore the name for the existing node doesn't change).
  1490. // Otherwise, things like shortcut links between nodes won't work.
  1491. template <typename T>
  1492. void
  1493. RBTree<T>::nodeFission(util::MemorySegment& mem_sgmt, RBNode<T>& node,
  1494. const isc::dns::LabelSequence& new_prefix,
  1495. const isc::dns::LabelSequence& new_suffix)
  1496. {
  1497. // Create and reset the labels.
  1498. // Once a new node is created, no exception will be thrown until
  1499. // the end of the function, and it will keep consistent behavior
  1500. // (i.e., a weak form of strong exception guarantee) even if code
  1501. // after the call to this function throws an exception.
  1502. RBNode<T>* down_node = RBNode<T>::create(mem_sgmt, new_prefix);
  1503. node.resetLabels(new_suffix);
  1504. std::swap(node.data_, down_node->data_);
  1505. // Swap flags bitfields; yes, this is ugly. The right solution is to
  1506. // implement the above note, then we won't have to swap the flags in the
  1507. // first place.
  1508. struct {
  1509. uint32_t flags_ : 23;
  1510. uint32_t unused_ : 9;
  1511. } tmp;
  1512. tmp.flags_ = node.flags_;
  1513. node.flags_ = down_node->flags_;
  1514. down_node->flags_ = tmp.flags_;
  1515. down_node->down_ = node.getDown();
  1516. node.down_ = down_node;
  1517. // Restore the color of the node (may have gotten changed by the flags
  1518. // swap)
  1519. node.setColor(down_node->getColor());
  1520. // root node of sub tree, the initial color is BLACK
  1521. down_node->setColor(RBNode<T>::BLACK);
  1522. // mark it as the root of a subtree
  1523. down_node->setSubTreeRoot(true);
  1524. ++node_count_;
  1525. }
  1526. template <typename T>
  1527. void
  1528. RBTree<T>::insertRebalance(typename RBNode<T>::RBNodePtr* root,
  1529. RBNode<T>* node)
  1530. {
  1531. RBNode<T>* uncle;
  1532. RBNode<T>* parent;
  1533. while (node != (*root).get() &&
  1534. (parent = node->getParent())->getColor() == RBNode<T>::RED) {
  1535. if (parent == parent->getParent()->getLeft()) {
  1536. uncle = parent->getParent()->getRight();
  1537. if (uncle->getColor() == RBNode<T>::RED) {
  1538. parent->setColor(RBNode<T>::BLACK);
  1539. uncle->setColor(RBNode<T>::BLACK);
  1540. parent->getParent()->setColor(RBNode<T>::RED);
  1541. node = parent->getParent();
  1542. } else {
  1543. if (node == parent->getRight()) {
  1544. node = parent;
  1545. leftRotate(root, node);
  1546. parent = node->getParent();
  1547. }
  1548. parent->setColor(RBNode<T>::BLACK);
  1549. parent->getParent()->setColor(RBNode<T>::RED);
  1550. rightRotate(root, parent->getParent());
  1551. }
  1552. } else {
  1553. uncle = parent->getParent()->getLeft();
  1554. if (uncle->getColor() == RBNode<T>::RED) {
  1555. parent->setColor(RBNode<T>::BLACK);
  1556. uncle->setColor(RBNode<T>::BLACK);
  1557. parent->getParent()->setColor(RBNode<T>::RED);
  1558. node = parent->getParent();
  1559. } else {
  1560. if (node == parent->getLeft()) {
  1561. node = parent;
  1562. rightRotate(root, node);
  1563. parent = node->getParent();
  1564. }
  1565. parent->setColor(RBNode<T>::BLACK);
  1566. parent->getParent()->setColor(RBNode<T>::RED);
  1567. leftRotate(root, parent->getParent());
  1568. }
  1569. }
  1570. }
  1571. (*root)->setColor(RBNode<T>::BLACK);
  1572. }
  1573. template <typename T>
  1574. RBNode<T>*
  1575. RBTree<T>::leftRotate(typename RBNode<T>::RBNodePtr* root, RBNode<T>* node) {
  1576. RBNode<T>* const right = node->getRight();
  1577. RBNode<T>* const rleft = right->getLeft();
  1578. node->right_ = rleft;
  1579. if (rleft != NULLNODE) {
  1580. rleft->parent_ = node;
  1581. rleft->setSubTreeRoot(false);
  1582. } else {
  1583. rleft->setSubTreeRoot(true);
  1584. }
  1585. RBNode<T>* const parent = node->getParent();
  1586. right->parent_ = parent;
  1587. if (parent != NULLNODE) {
  1588. right->setSubTreeRoot(false);
  1589. if (node == parent->getLeft()) {
  1590. parent->left_ = right;
  1591. } else {
  1592. parent->right_ = right;
  1593. }
  1594. } else {
  1595. right->setSubTreeRoot(true);
  1596. *root = right;
  1597. }
  1598. right->left_ = node;
  1599. node->parent_ = right;
  1600. node->setSubTreeRoot(false);
  1601. return (node);
  1602. }
  1603. template <typename T>
  1604. RBNode<T>*
  1605. RBTree<T>::rightRotate(typename RBNode<T>::RBNodePtr* root, RBNode<T>* node) {
  1606. RBNode<T>* const left = node->getLeft();
  1607. RBNode<T>* const lright = left->getRight();
  1608. node->left_ = lright;
  1609. if (lright != NULLNODE) {
  1610. lright->parent_ = node;
  1611. lright->setSubTreeRoot(false);
  1612. } else {
  1613. lright->setSubTreeRoot(false);
  1614. }
  1615. RBNode<T>* const parent = node->getParent();
  1616. left->parent_ = parent;
  1617. if (node->getParent() != NULLNODE) {
  1618. left->setSubTreeRoot(false);
  1619. if (node == parent->getRight()) {
  1620. parent->right_ = left;
  1621. } else {
  1622. parent->left_ = left;
  1623. }
  1624. } else {
  1625. left->setSubTreeRoot(true);
  1626. *root = left;
  1627. }
  1628. left->right_ = node;
  1629. node->parent_ = left;
  1630. node->setSubTreeRoot(false);
  1631. return (node);
  1632. }
  1633. template <typename T>
  1634. void
  1635. RBTree<T>::dumpTree(std::ostream& os, unsigned int depth) const {
  1636. indent(os, depth);
  1637. os << "tree has " << node_count_ << " node(s)\n";
  1638. dumpTreeHelper(os, root_.get(), depth);
  1639. }
  1640. template <typename T>
  1641. void
  1642. RBTree<T>::dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  1643. unsigned int depth) const
  1644. {
  1645. if (node == NULLNODE) {
  1646. indent(os, depth);
  1647. os << "NULL\n";
  1648. return;
  1649. }
  1650. indent(os, depth);
  1651. os << node->getLabels() << " ("
  1652. << ((node->getColor() == RBNode<T>::BLACK) ? "black" : "red")
  1653. << ")";
  1654. if (node->isEmpty()) {
  1655. os << " [invisible]";
  1656. }
  1657. if (node->isSubTreeRoot()) {
  1658. os << " [subtreeroot]";
  1659. }
  1660. os << "\n";
  1661. const RBNode<T>* down = node->getDown();
  1662. if (down != NULLNODE) {
  1663. indent(os, depth + 1);
  1664. os << "begin down from " << node->getLabels() << "\n";
  1665. dumpTreeHelper(os, down, depth + 1);
  1666. indent(os, depth + 1);
  1667. os << "end down from " << node->getLabels() << "\n";
  1668. }
  1669. dumpTreeHelper(os, node->getLeft(), depth + 1);
  1670. dumpTreeHelper(os, node->getRight(), depth + 1);
  1671. }
  1672. template <typename T>
  1673. void
  1674. RBTree<T>::indent(std::ostream& os, unsigned int depth) {
  1675. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  1676. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  1677. }
  1678. }
  1679. }
  1680. #endif // _RBTREE_H
  1681. // Local Variables:
  1682. // mode: c++
  1683. // End: