rbtree.h 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  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 <dns/name.h>
  25. #include <boost/utility.hpp>
  26. #include <boost/shared_ptr.hpp>
  27. #include <exceptions/exceptions.h>
  28. #include <ostream>
  29. #include <algorithm>
  30. #include <cassert>
  31. namespace isc {
  32. namespace datasrc {
  33. namespace helper {
  34. /// \brief Helper function to remove the base domain from super domain.
  35. ///
  36. /// The precondition of this function is the super_name contains the
  37. /// sub_name so
  38. /// \code Name a("a.b.c");
  39. /// Name b("b.c");
  40. /// Name c = a - b;
  41. /// \endcode
  42. /// c will contain "a".
  43. ///
  44. /// \note Functions in this namespace is not intended to be used outside of
  45. /// RBTree implementation.
  46. inline isc::dns::Name
  47. operator-(const isc::dns::Name& super_name, const isc::dns::Name& sub_name) {
  48. return (super_name.split(0, super_name.getLabelCount() -
  49. sub_name.getLabelCount()));
  50. }
  51. }
  52. /// Forward declare RBTree class here is convinent for following friend
  53. /// class declare inside RBNode and RBTreeNodeChain
  54. template <typename T>
  55. class RBTree;
  56. /// \brief \c RBNode is used by RBTree to store any data related to one domain
  57. /// name.
  58. ///
  59. /// This is meant to be used only from RBTree. It is meaningless to inherit it
  60. /// or create instances of it from elsewhere. For that reason, the constructor
  61. /// is private.
  62. ///
  63. /// It serves three roles. One is to keep structure of the \c RBTree as a
  64. /// red-black tree. For that purpose, it has left, right and parent pointers
  65. /// and color member. These are private and accessed only from within the tree.
  66. ///
  67. /// The second one is to store data for one domain name. The data related
  68. /// functions can be used to access and set the data.
  69. ///
  70. /// The third role is to keep the hierarchy of domains. The down pointer points
  71. /// to a subtree of subdomains. Note that we can traverse the hierarchy down,
  72. /// but not up.
  73. ///
  74. /// One special kind of node is non-terminal node. It has subdomains with
  75. /// RRsets, but doesn't have any RRsets itself.
  76. template <typename T>
  77. class RBNode : public boost::noncopyable {
  78. private:
  79. /// The RBNode is meant for use from within RBTree, so it has access to
  80. /// it.
  81. friend class RBTree<T>;
  82. /// \name Constructors
  83. ///
  84. /// \note The existence of a RBNode without a RBTree is meaningless.
  85. /// Therefore the constructors are private.
  86. //@{
  87. /// \brief Default constructor.
  88. ///
  89. /// This constructor is provided specifically for generating a special
  90. /// "null" node.
  91. RBNode();
  92. /// \brief Constructor from the node name.
  93. ///
  94. /// \param name The *relative* domain name (if this will live inside
  95. /// a.b.c and is called d.e.a.b.c, then you pass d.e).
  96. RBNode(const isc::dns::Name& name);
  97. //@}
  98. public:
  99. /// \brief Alias for shared pointer to the data.
  100. typedef boost::shared_ptr<T> NodeDataPtr;
  101. /// Node flags.
  102. ///
  103. /// Each flag value defines a non default property for a specific node.
  104. /// These are defined as bitmask type values for the convenience of
  105. /// internal implementation, but applications are expected to use
  106. /// each flag separately via the enum definitions.
  107. ///
  108. /// All (settable) flags are off by default; they must be explicitly
  109. /// set to on by the \c setFlag() method.
  110. enum Flags {
  111. FLAG_CALLBACK = 1, ///< Callback enabled. See \ref callback
  112. FLAG_USER1 = 0x80000000U, ///< Application specific flag
  113. FLAG_USER2 = 0x40000000U ///< Application specific flag
  114. };
  115. private:
  116. // Some flag values are expected to be used for internal purposes
  117. // (e.g., representing the node color) in future versions, so we
  118. // limit the settable flags via the \c setFlag() method to those
  119. // explicitly defined in \c Flags. This constant represents all
  120. // such flags.
  121. static const uint32_t SETTABLE_FLAGS = (FLAG_CALLBACK | FLAG_USER1 |
  122. FLAG_USER2);
  123. public:
  124. /// \brief Destructor
  125. ///
  126. /// It might seem strange that constructors are private and destructor
  127. /// public, but this is needed because of shared pointers need access
  128. /// to the destructor.
  129. ///
  130. /// You should never call anything like:
  131. /// \code delete pointer_to_node; \endcode
  132. /// The RBTree handles both creation and destructoion of nodes.
  133. ~RBNode();
  134. /// \name Getter functions.
  135. //@{
  136. /// \brief Return the name of current node.
  137. ///
  138. /// It's relative to its containing node.
  139. ///
  140. /// To get the absolute name of one node, the node path from the top node
  141. /// to current node has to be recorded.
  142. const isc::dns::Name& getName() const { return (name_); }
  143. /// \brief Return the data stored in this node.
  144. ///
  145. /// You should not delete the data, it is handled by shared pointers.
  146. NodeDataPtr& getData() { return (data_); }
  147. /// \brief Return the data stored in this node.
  148. const NodeDataPtr& getData() const { return (data_); }
  149. /// \brief return whether the node has related data.
  150. ///
  151. /// There can be empty nodes inside the RBTree. They are usually the
  152. /// non-terminal domains, but it is possible (yet probably meaningless)
  153. /// empty nodes anywhere.
  154. bool isEmpty() const { return (data_.get() == NULL); }
  155. //@}
  156. /// \name Setter functions.
  157. //@{
  158. /// \brief Set the data stored in the node.
  159. void setData(const NodeDataPtr& data) { data_ = data; }
  160. //@}
  161. /// \name Node flag manipulation methods
  162. //@{
  163. /// Get the status of a node flag.
  164. ///
  165. /// This method returns whether the given node flag is set (enabled)
  166. /// on the node. The \c flag parameter is expected to be one of the
  167. /// defined \c Flags constants. For simplicity, the method interface
  168. /// does not prohibit passing an undefined flag or combined flags, but
  169. /// the return value in such a case will be meaningless for the caller
  170. /// (an application would have to use an ugly cast for such an unintended
  171. /// form of call, which will hopefully avoid accidental misuse).
  172. ///
  173. /// \exception None
  174. /// \param flag The flag to be tested.
  175. /// \return \c true if the \c flag is set; \c false otherwise.
  176. bool getFlag(Flags flag) const {
  177. return ((flags_ & flag) != 0);
  178. }
  179. /// Set or clear a node flag.
  180. ///
  181. /// This method changes the status of the specified node flag to either
  182. /// "on" (enabled) or "off" (disabled). The new status is specified by
  183. /// the \c on parameter.
  184. /// Like the \c getFlag() method, \c flag is expected to be one of the
  185. /// defined \c Flags constants. If an undefined or unsettable flag is
  186. /// specified, \c isc::InvalidParameter exception will be thrown.
  187. ///
  188. /// \exception isc::InvalidParameter Unsettable flag is specified
  189. /// \exception None otherwise
  190. /// \param flag The node flag to be changed.
  191. /// \param on If \c true, set the flag to on; otherwise set it to off.
  192. void setFlag(Flags flag, bool on = true) {
  193. if ((flag & ~SETTABLE_FLAGS) != 0) {
  194. isc_throw(isc::InvalidParameter,
  195. "Unsettable RBTree flag is being set");
  196. }
  197. if (on) {
  198. flags_ |= flag;
  199. } else {
  200. flags_ &= ~flag;
  201. }
  202. }
  203. //@}
  204. private:
  205. /// \name Callback related methods
  206. ///
  207. /// See the description of \c RBTree<T>::find() at \ref callback
  208. /// about callbacks.
  209. ///
  210. /// These methods never throw an exception.
  211. //@{
  212. /// Return if callback is enabled at the node.
  213. //@}
  214. private:
  215. /// \brief Define rbnode color
  216. enum RBNodeColor {BLACK, RED};
  217. /// This is a factory class method of a special singleton null node.
  218. static RBNode<T>* NULL_NODE() {
  219. static RBNode<T> null_node;
  220. return (&null_node);
  221. }
  222. /// \brief return the next node which is bigger than current node
  223. /// in the same subtree
  224. ///
  225. /// The next successor for this node is the next bigger node in terms of
  226. /// the DNSSEC order relation within the same single subtree.
  227. /// Note that it may NOT be the next bigger node in the entire RBTree;
  228. /// RBTree is a tree in tree, and the real next node may reside in
  229. /// an upper or lower subtree of the subtree where this node belongs.
  230. /// For example, if this node has a sub domain, the real next node is
  231. /// the smallest node in the sub domain tree.
  232. ///
  233. /// If this node is the biggest node within the subtree, this method
  234. /// returns \c NULL_NODE().
  235. ///
  236. /// This method never throws an exception.
  237. const RBNode<T>* successor() const;
  238. /// \name Data to maintain the rbtree structure.
  239. //@{
  240. RBNode<T>* parent_;
  241. RBNode<T>* left_;
  242. RBNode<T>* right_;
  243. RBNodeColor color_;
  244. //@}
  245. /// \brief Relative name of the node.
  246. isc::dns::Name name_;
  247. /// \brief Data stored here.
  248. NodeDataPtr data_;
  249. /// \brief The subdomain tree.
  250. ///
  251. /// This points to the root node of trees of subdomains of this domain.
  252. ///
  253. /// \par Adding down pointer to \c RBNode has two purposes:
  254. /// \li Accelerate the search process, with sub domain tree, it splits the
  255. /// big flat tree into several hierarchy trees.
  256. /// \li It saves memory useage as it allows storing only relative names,
  257. /// avoiding storage of the same domain labels multiple times.
  258. RBNode<T>* down_;
  259. /// \brief If callback should be called when traversing this node in
  260. /// RBTree::find().
  261. ///
  262. /// \todo It might be needed to put it into more general attributes field.
  263. uint32_t flags_;
  264. };
  265. // This is only to support NULL nodes.
  266. template <typename T>
  267. RBNode<T>::RBNode() :
  268. parent_(NULL),
  269. left_(NULL),
  270. right_(NULL),
  271. color_(BLACK),
  272. // dummy name, the value doesn't matter:
  273. name_(isc::dns::Name::ROOT_NAME()),
  274. down_(NULL),
  275. flags_(0)
  276. {
  277. // Some compilers object to use of "this" in initializer lists.
  278. parent_ = this;
  279. left_ = this;
  280. right_ = this;
  281. down_ = this;
  282. }
  283. template <typename T>
  284. RBNode<T>::RBNode(const isc::dns::Name& name) :
  285. parent_(NULL_NODE()),
  286. left_(NULL_NODE()),
  287. right_(NULL_NODE()),
  288. color_(RED),
  289. name_(name),
  290. down_(NULL_NODE()),
  291. flags_(0)
  292. {
  293. }
  294. template <typename T>
  295. RBNode<T>::~RBNode() {
  296. }
  297. template <typename T>
  298. const RBNode<T>*
  299. RBNode<T>::successor() const {
  300. const RBNode<T>* current = this;
  301. // If it has right node, the successor is the left-most node of the right
  302. // subtree.
  303. if (right_ != NULL_NODE()) {
  304. current = right_;
  305. while (current->left_ != NULL_NODE()) {
  306. current = current->left_;
  307. }
  308. return (current);
  309. }
  310. // Otherwise go up until we find the first left branch on our path to
  311. // root. If found, the parent of the branch is the successor.
  312. // Otherwise, we return the null node
  313. const RBNode<T>* parent = current->parent_;
  314. while (parent != NULL_NODE() && current == parent->right_) {
  315. current = parent;
  316. parent = parent->parent_;
  317. }
  318. return (parent);
  319. }
  320. /// \brief RBTreeNodeChain stores detailed information of \c RBTree::find()
  321. /// result.
  322. ///
  323. /// - The \c RBNode that was last compared with the search name, and
  324. /// the comparison result at that point in the form of
  325. /// \c isc::dns::NameComparisonResult.
  326. /// - A sequence of nodes that forms a path to the found node (which is
  327. /// not yet implemented).
  328. ///
  329. /// The comparison result can be used to handle some rare cases such as
  330. /// empty node processing.
  331. /// The node sequence keeps track of the nodes to reach any given node from
  332. /// the root of RBTree.
  333. ///
  334. /// Currently, RBNode does not have "up" pointers in them (i.e., back pointers
  335. /// from the root of one level of tree of trees to the node in the parent
  336. /// tree whose down pointer points to that root node) for memory usage
  337. /// reasons, so there is no other way to find the path back to the root from
  338. /// any given RBNode.
  339. ///
  340. /// \note This design may change in future versions. In particular, it's
  341. /// quite likely we want to have that pointer if we want to optimize name
  342. /// compression by exploiting the structure of the zone. If and when that
  343. /// happens we should also revisit the need for the chaining.
  344. /// Also, the class name may not be appropriate now that it contains other
  345. /// information than a node "chain", and the chain itself may even be
  346. /// deprecated. Something like "RBTreeFindContext" may be a better name.
  347. /// This point should be revisited later.
  348. ///
  349. /// RBTreeNodeChain is constructed and manipulated only inside the \c RBTree
  350. /// class.
  351. /// \c RBTree uses it as an inner data structure to iterate over the whole
  352. /// RBTree.
  353. /// This is the reason why manipulation methods such as \c push() and \c pop()
  354. /// are private (and not shown in the doxygen document).
  355. template <typename T>
  356. class RBTreeNodeChain {
  357. /// RBTreeNodeChain is initialized by RBTree, only RBTree has
  358. /// knowledge to manipuate it.
  359. friend class RBTree<T>;
  360. public:
  361. /// \name Constructors and Assignment Operator.
  362. ///
  363. /// \note The copy constructor and the assignment operator are
  364. /// intentionally defined as private, making this class non copyable.
  365. /// This may have to be changed in a future version with newer need.
  366. /// For now we explicitly disable copy to avoid accidental copy happens
  367. /// unintentionally.
  368. //{@
  369. /// The default constructor.
  370. ///
  371. /// \exception None
  372. RBTreeNodeChain() : node_count_(0), last_compared_(NULL),
  373. // XXX: meaningless initial values:
  374. last_comparison_(0, 0,
  375. isc::dns::NameComparisonResult::EQUAL)
  376. {}
  377. private:
  378. RBTreeNodeChain(const RBTreeNodeChain<T>&);
  379. RBTreeNodeChain<T>& operator=(const RBTreeNodeChain<T>&);
  380. //@}
  381. public:
  382. /// Clear the state of the chain.
  383. ///
  384. /// This method re-initializes the internal state of the chain so that
  385. /// it can be reused for subsequent operations.
  386. ///
  387. /// \exception None
  388. void clear() {
  389. node_count_ = 0;
  390. last_compared_ = NULL;
  391. }
  392. /// Return the \c RBNode that was last compared in \c RBTree::find().
  393. ///
  394. /// If this chain has been passed to \c RBTree::find() and there has
  395. /// been name comparison against the search name, the last compared
  396. /// \c RBNode is recorded within the chain. This method returns that
  397. /// node.
  398. /// If \c RBTree::find() hasn't been called with this chain or name
  399. /// comparison hasn't taken place (which is possible if the tree is empty),
  400. /// this method returns \c NULL.
  401. ///
  402. /// \exception None
  403. const RBNode<T>* getLastComparedNode() const {
  404. return (last_compared_);
  405. }
  406. /// Return the result of last name comparison in \c RBTree::find().
  407. ///
  408. /// Like \c getLastComparedNode(), \c RBTree::find() records the result
  409. /// of the last name comparison in the chain. This method returns the
  410. /// result.
  411. /// The return value of this method is only meaningful when comparison
  412. /// has taken place, i.e, when \c getLastComparedNode() would return a
  413. /// non \c NULL value.
  414. ///
  415. /// \exception None
  416. const isc::dns::NameComparisonResult& getLastComparisonResult() const {
  417. return (last_comparison_);
  418. }
  419. /// \brief Return the number of levels stored in the chain.
  420. ///
  421. /// It's equal to the number of nodes in the chain; for an empty
  422. /// chain, 0 will be returned.
  423. ///
  424. /// \exception None
  425. unsigned int getLevelCount() const { return (node_count_); }
  426. /// \brief return the absolute name for the node which this
  427. /// \c RBTreeNodeChain currently refers to.
  428. ///
  429. /// The chain must not be empty.
  430. ///
  431. /// \exception isc::BadValue the chain is empty.
  432. /// \exception std::bad_alloc memory allocation for the new name fails.
  433. isc::dns::Name getAbsoluteName() const {
  434. if (isEmpty()) {
  435. isc_throw(isc::BadValue,
  436. "RBTreeNodeChain::getAbsoluteName is called on an empty "
  437. "chain");
  438. }
  439. const RBNode<T>* top_node = top();
  440. isc::dns::Name absolute_name = top_node->getName();
  441. int node_count = node_count_ - 1;
  442. while (node_count > 0) {
  443. top_node = nodes_[node_count - 1];
  444. absolute_name = absolute_name.concatenate(top_node->getName());
  445. --node_count;
  446. }
  447. return (absolute_name);
  448. }
  449. private:
  450. // the following private functions check invariants about the internal
  451. // state using assert() instead of exception. The state of a chain
  452. // can only be modified operations within this file, so if any of the
  453. // assumptions fails it means an internal bug.
  454. /// \brief return whther node chain has node in it.
  455. ///
  456. /// \exception None
  457. bool isEmpty() const { return (node_count_ == 0); }
  458. /// \brief return the top node for the node chain
  459. ///
  460. /// RBTreeNodeChain store all the nodes along top node to
  461. /// root node of RBTree
  462. ///
  463. /// \exception None
  464. const RBNode<T>* top() const {
  465. assert(!isEmpty());
  466. return (nodes_[node_count_ - 1]);
  467. }
  468. /// \brief pop the top node from the node chain
  469. ///
  470. /// After pop, up/super node of original top node will be
  471. /// the top node
  472. ///
  473. /// \exception None
  474. void pop() {
  475. assert(!isEmpty());
  476. --node_count_;
  477. }
  478. /// \brief add the node into the node chain
  479. ///
  480. /// If the node chain isn't empty, the node should be
  481. /// the sub domain of the original top node in node chain
  482. /// otherwise the node should be the root node of RBTree.
  483. ///
  484. /// \exception None
  485. void push(const RBNode<T>* node) {
  486. assert(node_count_ < RBT_MAX_LEVEL);
  487. nodes_[node_count_++] = node;
  488. }
  489. private:
  490. // The max label count for one domain name is Name::MAX_LABELS (128).
  491. // Since each node in rbtree stores at least one label, it's also equal
  492. // to the possible maximum level.
  493. const static int RBT_MAX_LEVEL = isc::dns::Name::MAX_LABELS;
  494. int node_count_;
  495. const RBNode<T>* nodes_[RBT_MAX_LEVEL];
  496. const RBNode<T>* last_compared_;
  497. isc::dns::NameComparisonResult last_comparison_;
  498. };
  499. // note: the following class description is documented using multiline comments
  500. // because the verbatim diagram contain a backslash, which could be interpreted
  501. // as escape of newline in singleline comment.
  502. /**
  503. * \brief \c RBTree class represents all the domains with the same suffix.
  504. * It can be used to store the domains in one zone, for example.
  505. *
  506. * RBTree is a generic map from domain names to any kind of data. Internally,
  507. * it uses a red-black tree. However, it isn't one tree containing everything.
  508. * Subdomains are trees, so this structure is recursive - trees inside trees.
  509. * But, from the interface point of view, it is opaque data structure.
  510. *
  511. * \c RBTree splits the domain space into hierarchy red black trees; nodes
  512. * in one tree has the same base name. The benefit of this struct is that:
  513. * - Enhances the query performace compared with one big flat red black tree.
  514. * - Decreases the memory footprint, as it doesn't store the suffix labels
  515. * multiple times.
  516. *
  517. * Depending on different usage, rbtree will support different search policies.
  518. * Whether to return an empty node to end user is one policy among them.
  519. * The default policy is to NOT return an empty node to end user;
  520. * to change the behavior, specify \c true for the constructor parameter
  521. * \c returnEmptyNode.
  522. * \note The search policy only affects the \c find() behavior of RBTree.
  523. * When inserting one name into RBTree, if the node with the name already
  524. * exists in the RBTree and it's an empty node which doesn't have any data,
  525. * the \c insert() method will still return \c ALREADYEXISTS regardless of
  526. * the search policy.
  527. *
  528. * \anchor diagram
  529. *
  530. * with the following names:
  531. * - a
  532. * - b
  533. * - c
  534. * - x.d.e.f
  535. * - z.d.e.f
  536. * - g.h
  537. * - o.w.y.d.e.f
  538. * - p.w.y.d.e.f
  539. * - q.w.y.d.e.f
  540. *
  541. * the tree will look like:
  542. * \verbatim
  543. b
  544. / \
  545. a d.e.f
  546. /|\
  547. c | g.h
  548. |
  549. w.y
  550. /|\
  551. x | z
  552. |
  553. p
  554. / \
  555. o q
  556. \endverbatim
  557. * \todo
  558. * - add remove interface
  559. * - add iterator to iterate over the whole \c RBTree. This may be necessary,
  560. * for example, to support AXFR.
  561. */
  562. template <typename T>
  563. class RBTree : public boost::noncopyable {
  564. friend class RBNode<T>;
  565. public:
  566. /// \brief The return value for the \c find() and insert() methods
  567. enum Result {
  568. SUCCESS, ///< Insert was successful
  569. /// \brief The node returned from find mathes exactly the name given
  570. EXACTMATCH,
  571. PARTIALMATCH, ///< A superdomain node was found
  572. NOTFOUND, ///< Not even any superdomain was found
  573. /// \brief Returned by insert() if a node of the name already exists
  574. ALREADYEXISTS,
  575. };
  576. /// \name Constructor and Destructor
  577. //@{
  578. /// The constructor.
  579. ///
  580. /// It never throws an exception.
  581. explicit RBTree(bool returnEmptyNode = false);
  582. /// \b Note: RBTree is not intended to be inherited so the destructor
  583. /// is not virtual
  584. ~RBTree();
  585. //@}
  586. /// \name Find methods
  587. ///
  588. /// \brief Find the node that gives a longest match against the given name.
  589. ///
  590. /// \anchor find
  591. ///
  592. /// These methods search the RBTree for a node whose name is longest
  593. /// against name. The found node, if any, is returned via the node pointer.
  594. ///
  595. /// By default, nodes that don't have data (see RBNode::isEmpty) are
  596. /// ignored and the result can be NOTFOUND even if there's a node whose
  597. /// name matches. If the \c RBTree is constructed with its
  598. /// \c returnEmptyNode parameter being \c true, an empty node will also
  599. /// be match candidates.
  600. ///
  601. /// \note Even when \c returnEmptyNode is \c true, not all empty nodes
  602. /// in terms of the DNS protocol may necessarily be found by this method.
  603. /// For example, in the \ref diagram shown in the class description,
  604. /// the name y.d.e.f is logically contained in the tree as part of the
  605. /// node w.y, but the \c find() variants cannot find the former for
  606. /// the search key of y.d.e.f, no matter how the \c RBTree is constructed.
  607. /// The caller of this method must use a different way to identify the
  608. /// hidden match when necessary.
  609. ///
  610. /// These methods involve operations on names that can throw an exception.
  611. /// If that happens the exception will be propagated to the caller.
  612. /// The callback function should generally not throw an exception, but
  613. /// if it throws, the exception will be propagated to the caller.
  614. ///
  615. /// The \c name parameter says what should be found. The node parameter
  616. /// is output only and in case of EXACTMATCH and PARTIALMATCH, it is set
  617. /// to a pointer to the found node.
  618. ///
  619. /// They return:
  620. /// - EXACTMATCH when a node with the same name as requested exists.
  621. /// - PARTIALMATCH when a node with the same name does not exist (or is
  622. /// empty), but there's a (nonempty) superdomain of the requested one.
  623. /// The superdomain with longest name is returned through the node
  624. /// parameter. Beware that if you store a zone in the tree, you may get
  625. /// PARTIALMATCH with zone apex when the given domain name is not there.
  626. /// You should not try to delegate into another zone in that case.
  627. /// - NOTFOUND if there's no node with the same name nor any superdomain
  628. /// of it. In that case, node parameter is left intact.
  629. //@{
  630. /// \brief Simple find.
  631. ///
  632. /// Acts as described in the \ref find section.
  633. Result find(const isc::dns::Name& name, RBNode<T>** node) const {
  634. RBTreeNodeChain<T> node_path;
  635. return (find<void*>(name, node, node_path, NULL, NULL));
  636. }
  637. /// \brief Simple find returning immutable node.
  638. ///
  639. /// Acts as described in the \ref find section, but returns immutable node
  640. /// pointer.
  641. Result find(const isc::dns::Name& name, const RBNode<T>** node) const {
  642. RBTreeNodeChain<T> node_path;
  643. RBNode<T> *target_node = NULL;
  644. Result ret = (find<void*>(name, &target_node, node_path, NULL, NULL));
  645. if (ret != NOTFOUND) {
  646. *node = target_node;
  647. }
  648. return (ret);
  649. }
  650. /// \brief Find with callback and node chain.
  651. /// \anchor callback
  652. ///
  653. /// This version of \c find() is specifically designed for the backend
  654. /// of the \c InMemoryZoneFinder class, and implements all necessary
  655. /// features for that purpose. Other applications shouldn't need these
  656. /// additional features, and should normally use the simpler versions.
  657. ///
  658. /// This version of \c find() calls the callback whenever traversing (on
  659. /// the way from root down the tree) a marked node on the way down through
  660. /// the domain namespace (see \c RBNode::enableCallback and related
  661. /// functions).
  662. ///
  663. /// If you return true from the callback, the search is stopped and a
  664. /// PARTIALMATCH is returned with the given node. Note that this node
  665. /// doesn't really need to be the one with longest possible match.
  666. ///
  667. /// This callback mechanism was designed with zone cut (delegation)
  668. /// processing in mind. The marked nodes would be the ones at delegation
  669. /// points. It is not expected that any other applications would need
  670. /// callbacks; they should use the versions of find without callbacks.
  671. /// The callbacks are not general functors for the same reason - we don't
  672. /// expect it to be needed.
  673. ///
  674. /// Another special feature of this version is the ability to record
  675. /// more detailed information regarding the search result.
  676. ///
  677. /// This information will be returned via the \c node_path parameter,
  678. /// which is an object of class \c RBTreeNodeChain.
  679. /// The passed parameter must be empty.
  680. ///
  681. /// \note The rest of the description isn't yet implemented. It will be
  682. /// handled in Trac ticket #517.
  683. ///
  684. /// On success, the node sequence stoed in \c node_path will contain all
  685. /// the ancestor nodes from the found node towards the root.
  686. /// For example, if we look for o.w.y.d.e.f in the example \ref diagram,
  687. /// \c node_path will contain w.y and d.e.f; the \c top() node of the
  688. /// chain will be o, w.f and d.e.f will be stored below it.
  689. ///
  690. /// This feature can be used to get the absolute name for a node;
  691. /// to do so, we need to travel upside from the node toward the root,
  692. /// concatenating all ancestor names. With the current implementation
  693. /// it's not possible without a node chain, because there is a no pointer
  694. /// from the root of a subtree to the parent subtree (this may change
  695. /// in a future version). A node chain can also be used to find the next
  696. /// node of a given node in the entire RBTree; the \c nextNode() method
  697. /// takes a node chain as a parameter.
  698. ///
  699. /// \exception isc::BadValue node_path is not empty (not yet implemented).
  700. ///
  701. /// \param name Target to be found
  702. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  703. /// it will store a pointer to the matching node
  704. /// \param node_path Other search details will be stored (see the
  705. /// description)
  706. /// \param callback If non \c NULL, a call back function to be called
  707. /// at marked nodes (see above).
  708. /// \param callback_arg A caller supplied argument to be passed to
  709. /// \c callback.
  710. ///
  711. /// \return As described above, but in case of callback returning true,
  712. /// it returns immediately with the current node.
  713. template <typename CBARG>
  714. Result find(const isc::dns::Name& name,
  715. RBNode<T>** node,
  716. RBTreeNodeChain<T>& node_path,
  717. bool (*callback)(const RBNode<T>&, CBARG),
  718. CBARG callback_arg) const;
  719. /// \brief Simple find returning immutable node.
  720. ///
  721. /// Acts as described in the \ref find section, but returns immutable
  722. /// node pointer.
  723. template <typename CBARG>
  724. Result find(const isc::dns::Name& name,
  725. const RBNode<T>** node,
  726. RBTreeNodeChain<T>& node_path,
  727. bool (*callback)(const RBNode<T>&, CBARG),
  728. CBARG callback_arg) const
  729. {
  730. RBNode<T>* target_node = NULL;
  731. Result ret = find(name, &target_node, node_path, callback,
  732. callback_arg);
  733. if (ret != NOTFOUND) {
  734. *node = target_node;
  735. }
  736. return (ret);
  737. }
  738. //@}
  739. /// \brief return the next bigger node in DNSSEC order from a given node
  740. /// chain.
  741. ///
  742. /// This method identifies the next bigger node of the node currently
  743. /// referenced in \c node_path and returns it.
  744. /// This method also updates the passed \c node_path so that it will store
  745. /// the path for the returned next node.
  746. /// It will be convenient when we want to iterate over the all nodes
  747. /// of \c RBTree; we can do this by calling this method repeatedly
  748. /// starting from the root node.
  749. ///
  750. /// \note \c nextNode() will iterate over all the nodes in RBTree including
  751. /// empty nodes. If empty node isn't desired, it's easy to add logic to
  752. /// check return node and keep invoking \c nextNode() until the non-empty
  753. /// node is retrieved.
  754. ///
  755. /// \exception isc::BadValue node_path is empty.
  756. ///
  757. /// \param node_path A node chain that stores all the nodes along the path
  758. /// from root to node.
  759. ///
  760. /// \return An \c RBNode that is next bigger than \c node; if \c node is
  761. /// the largest, \c NULL will be returned.
  762. const RBNode<T>* nextNode(RBTreeNodeChain<T>& node_path) const;
  763. /// \brief Get the total number of nodes in the tree
  764. ///
  765. /// It includes nodes internally created as a result of adding a domain
  766. /// name that is a subdomain of an existing node of the tree.
  767. /// This function is mainly intended to be used for debugging.
  768. int getNodeCount() const { return (node_count_); }
  769. /// \name Debug function
  770. //@{
  771. /// \brief Print the nodes in the trees.
  772. ///
  773. /// \param os A \c std::ostream object to which the tree is printed.
  774. /// \param depth A factor of the initial indentation. Each line
  775. /// will begin with space character repeating <code>5 * depth</code>
  776. /// times.
  777. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  778. //@}
  779. /// \name Modify functions
  780. //@{
  781. /// \brief Insert the domain name into the tree.
  782. ///
  783. /// It either finds an already existing node of the given name or inserts
  784. /// a new one, if none exists yet. In any case, the inserted_node parameter
  785. /// is set to point to that node. You can fill data into it or modify it.
  786. /// So, if you don't know if a node exists or not and you need to modify
  787. /// it, just call insert and act by the result.
  788. ///
  789. /// Please note that the tree can add some empty nodes by itself, so don't
  790. /// assume that if you didn't insert a node of that name it doesn't exist.
  791. ///
  792. /// This method normally involves resource allocation. If it fails
  793. /// the corresponding standard exception will be thrown.
  794. ///
  795. /// This method does not provide the strong exception guarantee in its
  796. /// strict sense; if an exception is thrown in the middle of this
  797. /// method, the internal structure may change. However, it should
  798. /// still retain the same property as a mapping container before this
  799. /// method is called. For example, the result of \c find() should be
  800. /// the same. This method provides the weak exception guarantee in its
  801. /// normal sense.
  802. ///
  803. /// \param name The name to be inserted into the tree.
  804. /// \param inserted_node This is an output parameter and is set to the
  805. /// node.
  806. ///
  807. /// \return
  808. /// - SUCCESS The node was added.
  809. /// - ALREADYEXISTS There was already a node of that name, so it was not
  810. /// added.
  811. Result insert(const isc::dns::Name& name, RBNode<T>** inserted_node);
  812. /// \brief Swaps two tree's contents.
  813. ///
  814. /// This acts the same as many std::*.swap functions, exchanges the
  815. /// contents. This doesn't throw anything.
  816. void swap(RBTree<T>& other) {
  817. std::swap(root_, other.root_);
  818. std::swap(NULLNODE, other.NULLNODE);
  819. std::swap(node_count_, other.node_count_);
  820. }
  821. //@}
  822. private:
  823. /// \name RBTree balance functions
  824. //@{
  825. void insertRebalance(RBNode<T>** root, RBNode<T>* node);
  826. RBNode<T>* rightRotate(RBNode<T>** root, RBNode<T>* node);
  827. RBNode<T>* leftRotate(RBNode<T>** root, RBNode<T>* node);
  828. //@}
  829. /// \name Helper functions
  830. //@{
  831. /// \brief delete tree whose root is equal to node
  832. void deleteHelper(RBNode<T> *node);
  833. /// \brief Print the information of given RBNode.
  834. void dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  835. unsigned int depth) const;
  836. /// \brief Indentation helper function for dumpTree
  837. static void indent(std::ostream& os, unsigned int depth);
  838. /// Split one node into two nodes, keep the old node and create one new
  839. /// node, old node will hold the base name, new node will be the down node
  840. /// of old node, new node will hold the sub_name, the data
  841. /// of old node will be move into new node, and old node became non-terminal
  842. void nodeFission(RBNode<T>& node, const isc::dns::Name& sub_name);
  843. //@}
  844. RBNode<T>* NULLNODE;
  845. RBNode<T>* root_;
  846. /// the node count of current tree
  847. unsigned int node_count_;
  848. /// search policy for rbtree
  849. const bool needsReturnEmptyNode_;
  850. };
  851. template <typename T>
  852. RBTree<T>::RBTree(bool returnEmptyNode) :
  853. NULLNODE(RBNode<T>::NULL_NODE()),
  854. root_(NULLNODE),
  855. node_count_(0),
  856. needsReturnEmptyNode_(returnEmptyNode)
  857. {
  858. }
  859. template <typename T>
  860. RBTree<T>::~RBTree() {
  861. deleteHelper(root_);
  862. assert(node_count_ == 0);
  863. }
  864. template <typename T>
  865. void
  866. RBTree<T>::deleteHelper(RBNode<T>* root) {
  867. if (root == NULLNODE) {
  868. return;
  869. }
  870. RBNode<T>* node = root;
  871. while (root->left_ != NULLNODE || root->right_ != NULLNODE) {
  872. while (node->left_ != NULLNODE || node->right_ != NULLNODE) {
  873. node = (node->left_ != NULLNODE) ? node->left_ : node->right_;
  874. }
  875. RBNode<T>* parent = node->parent_;
  876. if (parent->left_ == node) {
  877. parent->left_ = NULLNODE;
  878. } else {
  879. parent->right_ = NULLNODE;
  880. }
  881. deleteHelper(node->down_);
  882. delete node;
  883. --node_count_;
  884. node = parent;
  885. }
  886. deleteHelper(root->down_);
  887. delete root;
  888. --node_count_;
  889. }
  890. template <typename T>
  891. template <typename CBARG>
  892. typename RBTree<T>::Result
  893. RBTree<T>::find(const isc::dns::Name& target_name,
  894. RBNode<T>** target,
  895. RBTreeNodeChain<T>& node_path,
  896. bool (*callback)(const RBNode<T>&, CBARG),
  897. CBARG callback_arg) const
  898. {
  899. using namespace helper;
  900. if (!node_path.isEmpty()) {
  901. isc_throw(isc::BadValue, "RBTree::find is given a non empty chain");
  902. }
  903. RBNode<T>* node = root_;
  904. Result ret = NOTFOUND;
  905. isc::dns::Name name = target_name;
  906. while (node != NULLNODE) {
  907. node_path.last_compared_ = node;
  908. node_path.last_comparison_ = name.compare(node->name_);
  909. const isc::dns::NameComparisonResult::NameRelation relation =
  910. node_path.last_comparison_.getRelation();
  911. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  912. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  913. node_path.push(node);
  914. *target = node;
  915. ret = EXACTMATCH;
  916. }
  917. break;
  918. } else {
  919. const int common_label_count =
  920. node_path.last_comparison_.getCommonLabels();
  921. // If the common label count is 1, there is no common label between
  922. // the two names, except the trailing "dot". In this case the two
  923. // sequences of labels have essentially no hierarchical
  924. // relationship in terms of matching, so we should continue the
  925. // binary search. One important exception is when the node
  926. // represents the root name ("."), in which case the comparison
  927. // result must indeed be considered subdomain matching. (We use
  928. // getLength() to check if the name is root, which is an equivalent
  929. // but cheaper way).
  930. if (common_label_count == 1 && node->name_.getLength() != 1) {
  931. node = (node_path.last_comparison_.getOrder() < 0) ?
  932. node->left_ : node->right_;
  933. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  934. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  935. ret = PARTIALMATCH;
  936. *target = node;
  937. if (callback != NULL &&
  938. node->getFlag(RBNode<T>::FLAG_CALLBACK)) {
  939. if ((callback)(*node, callback_arg)) {
  940. break;
  941. }
  942. }
  943. }
  944. node_path.push(node);
  945. name = name - node->name_;
  946. node = node->down_;
  947. } else {
  948. break;
  949. }
  950. }
  951. }
  952. return (ret);
  953. }
  954. template <typename T>
  955. const RBNode<T>*
  956. RBTree<T>::nextNode(RBTreeNodeChain<T>& node_path) const {
  957. if (node_path.isEmpty()) {
  958. isc_throw(isc::BadValue, "RBTree::nextNode is given an empty chain");
  959. }
  960. const RBNode<T>* node = node_path.top();
  961. // if node has sub domain, the next domain is the smallest
  962. // domain in sub domain tree
  963. if (node->down_ != NULLNODE) {
  964. const RBNode<T>* left_most = node->down_;
  965. while (left_most->left_ != NULLNODE) {
  966. left_most = left_most->left_;
  967. }
  968. node_path.push(left_most);
  969. return (left_most);
  970. }
  971. // node_path go to up level
  972. node_path.pop();
  973. // otherwise found the successor node in current level
  974. const RBNode<T>* successor = node->successor();
  975. if (successor != NULLNODE) {
  976. node_path.push(successor);
  977. return (successor);
  978. }
  979. // if no successor found move to up level, the next successor
  980. // is the successor of up node in the up level tree, if
  981. // up node doesn't have successor we gonna keep moving to up
  982. // level
  983. while (!node_path.isEmpty()) {
  984. const RBNode<T>* up_node_successor = node_path.top()->successor();
  985. node_path.pop();
  986. if (up_node_successor != NULLNODE) {
  987. node_path.push(up_node_successor);
  988. return (up_node_successor);
  989. }
  990. }
  991. return (NULL);
  992. }
  993. template <typename T>
  994. typename RBTree<T>::Result
  995. RBTree<T>::insert(const isc::dns::Name& target_name, RBNode<T>** new_node) {
  996. using namespace helper;
  997. RBNode<T>* parent = NULLNODE;
  998. RBNode<T>* current = root_;
  999. RBNode<T>* up_node = NULLNODE;
  1000. isc::dns::Name name = target_name;
  1001. int order = -1;
  1002. while (current != NULLNODE) {
  1003. const isc::dns::NameComparisonResult compare_result =
  1004. name.compare(current->name_);
  1005. const isc::dns::NameComparisonResult::NameRelation relation =
  1006. compare_result.getRelation();
  1007. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1008. if (new_node != NULL) {
  1009. *new_node = current;
  1010. }
  1011. return (ALREADYEXISTS);
  1012. } else {
  1013. const int common_label_count = compare_result.getCommonLabels();
  1014. // Note: see find() for the check of getLength().
  1015. if (common_label_count == 1 && current->name_.getLength() != 1) {
  1016. parent = current;
  1017. order = compare_result.getOrder();
  1018. current = order < 0 ? current->left_ : current->right_;
  1019. } else {
  1020. // insert sub domain to sub tree
  1021. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1022. parent = NULLNODE;
  1023. up_node = current;
  1024. name = name - current->name_;
  1025. current = current->down_;
  1026. } else {
  1027. // The number of labels in common is fewer
  1028. // than the number of labels at the current
  1029. // node, so the current node must be adjusted
  1030. // to have just the common suffix, and a down
  1031. // pointer made to a new tree.
  1032. const isc::dns::Name common_ancestor = name.split(
  1033. name.getLabelCount() - common_label_count,
  1034. common_label_count);
  1035. nodeFission(*current, common_ancestor);
  1036. }
  1037. }
  1038. }
  1039. }
  1040. RBNode<T>** current_root = (up_node != NULLNODE) ?
  1041. &(up_node->down_) : &root_;
  1042. // using auto_ptr here is avoid memory leak in case of exceptoin raised
  1043. // after the RBNode creation, if we can make sure no exception will be
  1044. // raised until the end of the function, we can remove it for optimization
  1045. std::auto_ptr<RBNode<T> > node(new RBNode<T>(name));
  1046. node->parent_ = parent;
  1047. if (parent == NULLNODE) {
  1048. *current_root = node.get();
  1049. //node is the new root of sub tree, so its init color
  1050. // is BLACK
  1051. node->color_ = RBNode<T>::BLACK;
  1052. } else if (order < 0) {
  1053. parent->left_ = node.get();
  1054. } else {
  1055. parent->right_ = node.get();
  1056. }
  1057. insertRebalance(current_root, node.get());
  1058. if (new_node != NULL) {
  1059. *new_node = node.get();
  1060. }
  1061. ++node_count_;
  1062. node.release();
  1063. return (SUCCESS);
  1064. }
  1065. template <typename T>
  1066. void
  1067. RBTree<T>::nodeFission(RBNode<T>& node, const isc::dns::Name& base_name) {
  1068. using namespace helper;
  1069. const isc::dns::Name sub_name = node.name_ - base_name;
  1070. // using auto_ptr here is to avoid memory leak in case of exception raised
  1071. // after the RBNode creation
  1072. std::auto_ptr<RBNode<T> > down_node(new RBNode<T>(sub_name));
  1073. node.name_ = base_name;
  1074. // the rest of this function should be exception free so that it keeps
  1075. // consistent behavior (i.e., a weak form of strong exception guarantee)
  1076. // even if code after the call to this function throws an exception.
  1077. std::swap(node.data_, down_node->data_);
  1078. std::swap(node.flags_, down_node->flags_);
  1079. down_node->down_ = node.down_;
  1080. node.down_ = down_node.get();
  1081. // root node of sub tree, the initial color is BLACK
  1082. down_node->color_ = RBNode<T>::BLACK;
  1083. ++node_count_;
  1084. down_node.release();
  1085. }
  1086. template <typename T>
  1087. void
  1088. RBTree<T>::insertRebalance(RBNode<T>** root, RBNode<T>* node) {
  1089. RBNode<T>* uncle;
  1090. while (node != *root && node->parent_->color_ == RBNode<T>::RED) {
  1091. if (node->parent_ == node->parent_->parent_->left_) {
  1092. uncle = node->parent_->parent_->right_;
  1093. if (uncle->color_ == RBNode<T>::RED) {
  1094. node->parent_->color_ = RBNode<T>::BLACK;
  1095. uncle->color_ = RBNode<T>::BLACK;
  1096. node->parent_->parent_->color_ = RBNode<T>::RED;
  1097. node = node->parent_->parent_;
  1098. } else {
  1099. if (node == node->parent_->right_) {
  1100. node = node->parent_;
  1101. leftRotate(root, node);
  1102. }
  1103. node->parent_->color_ = RBNode<T>::BLACK;
  1104. node->parent_->parent_->color_ = RBNode<T>::RED;
  1105. rightRotate(root, node->parent_->parent_);
  1106. }
  1107. } else {
  1108. uncle = node->parent_->parent_->left_;
  1109. if (uncle->color_ == RBNode<T>::RED) {
  1110. node->parent_->color_ = RBNode<T>::BLACK;
  1111. uncle->color_ = RBNode<T>::BLACK;
  1112. node->parent_->parent_->color_ = RBNode<T>::RED;
  1113. node = node->parent_->parent_;
  1114. } else {
  1115. if (node == node->parent_->left_) {
  1116. node = node->parent_;
  1117. rightRotate(root, node);
  1118. }
  1119. node->parent_->color_ = RBNode<T>::BLACK;
  1120. node->parent_->parent_->color_ = RBNode<T>::RED;
  1121. leftRotate(root, node->parent_->parent_);
  1122. }
  1123. }
  1124. }
  1125. (*root)->color_ = RBNode<T>::BLACK;
  1126. }
  1127. template <typename T>
  1128. RBNode<T>*
  1129. RBTree<T>::leftRotate(RBNode<T>** root, RBNode<T>* node) {
  1130. RBNode<T>* right = node->right_;
  1131. node->right_ = right->left_;
  1132. if (right->left_ != NULLNODE)
  1133. right->left_->parent_ = node;
  1134. right->parent_ = node->parent_;
  1135. if (node->parent_ != NULLNODE) {
  1136. if (node == node->parent_->left_) {
  1137. node->parent_->left_ = right;
  1138. } else {
  1139. node->parent_->right_ = right;
  1140. }
  1141. } else {
  1142. *root = right;
  1143. }
  1144. right->left_ = node;
  1145. node->parent_ = right;
  1146. return (node);
  1147. }
  1148. template <typename T>
  1149. RBNode<T>*
  1150. RBTree<T>::rightRotate(RBNode<T>** root, RBNode<T>* node) {
  1151. RBNode<T>* left = node->left_;
  1152. node->left_ = left->right_;
  1153. if (left->right_ != NULLNODE)
  1154. left->right_->parent_ = node;
  1155. left->parent_ = node->parent_;
  1156. if (node->parent_ != NULLNODE) {
  1157. if (node == node->parent_->right_) {
  1158. node->parent_->right_ = left;
  1159. } else {
  1160. node->parent_->left_ = left;
  1161. }
  1162. } else {
  1163. *root = left;
  1164. }
  1165. left->right_ = node;
  1166. node->parent_ = left;
  1167. return (node);
  1168. }
  1169. template <typename T>
  1170. void
  1171. RBTree<T>::dumpTree(std::ostream& os, unsigned int depth) const {
  1172. indent(os, depth);
  1173. os << "tree has " << node_count_ << " node(s)\n";
  1174. dumpTreeHelper(os, root_, depth);
  1175. }
  1176. template <typename T>
  1177. void
  1178. RBTree<T>::dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  1179. unsigned int depth) const
  1180. {
  1181. if (node == NULLNODE) {
  1182. indent(os, depth);
  1183. os << "NULL\n";
  1184. return;
  1185. }
  1186. indent(os, depth);
  1187. os << node->name_.toText() << " ("
  1188. << ((node->color_ == RBNode<T>::BLACK) ? "black" : "red") << ")";
  1189. os << ((node->isEmpty()) ? "[invisible] \n" : "\n");
  1190. if (node->down_ != NULLNODE) {
  1191. indent(os, depth + 1);
  1192. os << "begin down from " << node->name_.toText() << "\n";
  1193. dumpTreeHelper(os, node->down_, depth + 1);
  1194. indent(os, depth + 1);
  1195. os << "end down from " << node->name_.toText() << "\n";
  1196. }
  1197. dumpTreeHelper(os, node->left_, depth + 1);
  1198. dumpTreeHelper(os, node->right_, depth + 1);
  1199. }
  1200. template <typename T>
  1201. void
  1202. RBTree<T>::indent(std::ostream& os, unsigned int depth) {
  1203. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  1204. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  1205. }
  1206. }
  1207. }
  1208. #endif // _RBTREE_H
  1209. // Local Variables:
  1210. // mode: c++
  1211. // End: