rbtree.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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 <dns/name.h>
  24. #include <boost/utility.hpp>
  25. #include <boost/shared_ptr.hpp>
  26. #include <exception>
  27. #include <ostream>
  28. #include <algorithm>
  29. namespace isc {
  30. namespace datasrc {
  31. namespace helper {
  32. /// \brief Helper function to remove the base domain from super domain.
  33. ///
  34. /// The precondition of this function is the super_name contains the
  35. /// sub_name so
  36. /// \code Name a("a.b.c");
  37. /// Name b("b.c");
  38. /// Name c = a - b;
  39. /// \endcode
  40. /// c will contain "a".
  41. ///
  42. /// \note Functions in this namespace is not intended to be used outside of
  43. /// RBTree implementation.
  44. inline isc::dns::Name
  45. operator-(const isc::dns::Name& super_name, const isc::dns::Name& sub_name) {
  46. return (super_name.split(0, super_name.getLabelCount() -
  47. sub_name.getLabelCount()));
  48. }
  49. }
  50. template <typename T>
  51. class RBTree;
  52. /// \brief \c RBNode is use by RBTree to store any data related to one domain
  53. /// name.
  54. ///
  55. /// This is meant to be used only from RBTree. It is meaningless to inherit it
  56. /// or create instances of it from elsewhere. For that reason, the constructor
  57. /// is private.
  58. ///
  59. /// It serves three roles. One is to keep structure of the \c RBTree as a
  60. /// red-black tree. For that purpose, it has left, right and parent pointers
  61. /// and color member. These are private and accessed only from within the tree.
  62. ///
  63. /// The second one is to store data for one domain name. The data related
  64. /// functions can be used to access and set the data.
  65. ///
  66. /// The third role is to keep the hierarchy of domains. The down pointer points
  67. /// to a subtree of subdomains. Note that we can traverse the hierarchy down,
  68. /// but not up.
  69. ///
  70. /// One special kind of node is non-terminal node. It has subdomains with
  71. /// RRsets, but doesn't have any RRsets itself.
  72. template <typename T>
  73. class RBNode : public boost::noncopyable {
  74. private:
  75. /// The RBNode is meant for use from within RBTree, so it has access to
  76. /// it.
  77. friend class RBTree<T>;
  78. /// \name Constructors
  79. ///
  80. /// \note The existence of a RBNode without a RBTree is meaningless.
  81. /// Therefore the constructors are private.
  82. //@{
  83. /// \brief Default constructor.
  84. ///
  85. /// This constructor is provided specifically for generating a special
  86. /// "null" node.
  87. RBNode();
  88. /// \brief Constructor from the node name.
  89. ///
  90. /// \param name The *relative* domain name (if this will live inside
  91. /// a.b.c and is called d.e.a.b.c, then you pass d.e).
  92. RBNode(const isc::dns::Name& name);
  93. //@}
  94. public:
  95. /// \brief Alias for shared pointer to the data.
  96. typedef boost::shared_ptr<T> NodeDataPtr;
  97. /// \brief Destructor
  98. ///
  99. /// It might seem strange that constructors are private and destructor
  100. /// public, but this is needed because of shared pointers need access
  101. /// to the destructor.
  102. ///
  103. /// You should never call \code delete pointer_to_node; \endcode, the
  104. /// RBTree handles both creation and destructoion of nodes.
  105. ~RBNode();
  106. /// \name Getter functions.
  107. //@{
  108. /// \brief Return the name of current node.
  109. ///
  110. /// It's relative to its containing node.
  111. ///
  112. /// To get the absolute name of one node, the node path from the top node
  113. /// to current node has to be recorded.
  114. const isc::dns::Name& getName() const { return (name_); }
  115. /// \brief Return the data stored in this node.
  116. ///
  117. /// You should not delete the data, it is handled by shared pointers.
  118. NodeDataPtr& getData() { return (data_); }
  119. /// \brief Return the data stored in this node.
  120. const NodeDataPtr& getData() const { return (data_); }
  121. /// \brief return whether the node has related data.
  122. ///
  123. /// There can be empty nodes inside the RBTree. They are usually the
  124. /// non-terminal domains, but it is possible (yet probably meaningless)
  125. /// empty nodes anywhere.
  126. bool isEmpty() const { return (data_.get() == NULL); }
  127. //@}
  128. /// \name Setter functions.
  129. //@{
  130. /// \brief Set the data stored in the node.
  131. void setData(const NodeDataPtr& data) { data_ = data; }
  132. //@}
  133. /// \name Callback related methods
  134. ///
  135. /// See the description of \c RBTree<T>::find() about callbacks.
  136. ///
  137. /// These methods never throw an exception.
  138. //@{
  139. /// Return if callback is enabled at the node.
  140. bool isCallbackEnabled() const { return (callback_required_); }
  141. /// Enable callback at the node.
  142. void enableCallback() { callback_required_ = true; }
  143. /// Disable callback at the node.
  144. void disableCallback() { callback_required_ = false; }
  145. //@}
  146. private:
  147. /// \brief Define rbnode color
  148. enum RBNodeColor {BLACK, RED};
  149. /// This is a factory class method of a special singleton null node.
  150. static RBNode<T>* NULL_NODE() {
  151. static RBNode<T> null_node;
  152. return (&null_node);
  153. }
  154. /// \name Data to maintain the rbtree structure.
  155. //@{
  156. RBNode<T>* parent_;
  157. RBNode<T>* left_;
  158. RBNode<T>* right_;
  159. RBNodeColor color_;
  160. //@}
  161. /// \brief Relative name of the node.
  162. isc::dns::Name name_;
  163. /// \brief Data stored here.
  164. NodeDataPtr data_;
  165. /// \brief The subdomain tree.
  166. ///
  167. /// This points to the root node of trees of subdomains of this domain.
  168. ///
  169. /// \par Adding down pointer to \c RBNode has two purposes:
  170. /// \li Accelerate the search process, with sub domain tree, it splits the
  171. /// big flat tree into several hierarchy trees.
  172. /// \li It saves memory useage as it allows storing only relative names,
  173. /// avoiding storage of the same domain labels multiple times.
  174. RBNode<T>* down_;
  175. /// \brief If callback should be called when traversing this node in
  176. /// RBTree::find().
  177. ///
  178. /// \todo It might be needed to put it into more general attributes field.
  179. bool callback_required_;
  180. };
  181. // This is only to support NULL nodes.
  182. template <typename T>
  183. RBNode<T>::RBNode() :
  184. parent_(this),
  185. left_(this),
  186. right_(this),
  187. color_(BLACK),
  188. // dummy name, the value doesn't matter:
  189. name_(isc::dns::Name::ROOT_NAME()),
  190. down_(this),
  191. callback_required_(false)
  192. {
  193. }
  194. template <typename T>
  195. RBNode<T>::RBNode(const isc::dns::Name& name) :
  196. parent_(NULL_NODE()),
  197. left_(NULL_NODE()),
  198. right_(NULL_NODE()),
  199. color_(RED),
  200. name_(name),
  201. down_(NULL_NODE()),
  202. callback_required_(false)
  203. {
  204. }
  205. template <typename T>
  206. RBNode<T>::~RBNode() {
  207. }
  208. // note: the following class description is documented using C-style comments
  209. // because the verbatim diagram contain a backslash, which could be interpreted
  210. // as part of a multi-line comment with C++ style comments.
  211. /**
  212. * \brief \c RBTree class represents all the domains with the same suffix,
  213. * so it can be used to store the domains in one zone.
  214. *
  215. * \c RBTree is a generic red black tree, and contains all the nodes with
  216. * the same suffix, since each name may have sub domain names
  217. * so \c RBTree is a recursive data structure namely tree in tree.
  218. * So for one zone, several RBTrees may be involved. But from outside, the sub
  219. * tree is opaque for end users.
  220. *
  221. * \c RBTree split the domain space into hierarchy red black trees, nodes in one
  222. * tree has the same base name. The benefit of this struct is that:
  223. * - enhance the query performace compared with one big flat red black tree
  224. * - decrase the memory footprint to save common labels only once.
  225. *
  226. * \verbatim
  227. with the following names:
  228. a x.d.e.f o.w.y.d.e.f
  229. b z.d.e.f p.w.y.d.e.f
  230. c g.h q.w.y.d.e.f
  231. the tree will looks like:
  232. b
  233. / \
  234. a d.e.f
  235. /|\
  236. c | g.h
  237. |
  238. w.y
  239. /|\
  240. x | z
  241. |
  242. p
  243. / \
  244. o q
  245. * \endverbatim
  246. * \note open problems:
  247. * - current find funciton only return non-empty nodes, so there is no difference
  248. * between find one not exist name with empty non-terminal nodes, but in DNS query
  249. * logic, they are different
  250. * \todo
  251. * - add remove interface
  252. * - add iterator to iterate the whole rbtree while may needed by axfr
  253. * - since \c RBNode only has down pointer without up pointer, the node path during finding
  254. * should be recorded for later use
  255. */
  256. template <typename T>
  257. class RBTree : public boost::noncopyable {
  258. friend class RBNode<T>;
  259. public:
  260. /// \brief The return value for the \c find() insert() and erase() method
  261. enum Result {
  262. SUCCESS, //insert or erase succeed
  263. EXACTMATCH, //find the target name
  264. PARTIALMATCH, //find part of target name
  265. NOTFOUND, // for find function means no related name found
  266. // for erase function means erase not exist name
  267. ALREADYEXISTS, //for insert operation, the name to insert already exist
  268. };
  269. /// \name Constructor and Destructor
  270. //@{
  271. explicit RBTree();
  272. /// \b Note: RBTree is not intended to be inherited so the destructor
  273. /// is not virtual
  274. ~RBTree();
  275. //@}
  276. /// \name Inquery methods
  277. //@{
  278. /// \brief Find the node that gives a longest match against the given name
  279. ///
  280. /// This method searches the \c RBTree for a node whose name is a longest
  281. /// match against \c name. The found node, if any, is returned via the
  282. /// \c node pointer.
  283. /// By default, nodes that don't have data will be ignored, and the result
  284. /// can be \c NOTFOUND even if there is a node whose name matches the
  285. /// given \c name.
  286. /// We'll soon introduce a "no data OK" mode in this method. It would
  287. /// match any node of the tree regardless of whether the node has data
  288. /// or not.
  289. /// Since the tree is "compressed", i.e., a node can contain multiple
  290. /// name labels, there are counter intuitive cases in the "no data OK"
  291. /// mode. For example, see the diagram of the class description.
  292. /// Name "y.d.e.f" is logically contained in the tree as part of the
  293. /// "compressed" node of "w.y". But the search logic of this method
  294. /// cannot find the logical match, and would return a \c PARTIALMATCH
  295. /// result pointing to node "d.e.f". To correctly identify the real
  296. /// longest match, "y.d.e.f" with empty data, the caller needs to
  297. /// perform additional steps.
  298. ///
  299. /// This version of \c find() method is templated to allow the caller
  300. /// to specify a "hook" at nodes that give a partial match.
  301. /// When the search encounters a node with data that partially matches
  302. /// \c name (i.e. node's name is a superdomain of \c name) and has
  303. /// enabled callback (via the \c RBNode::enableCallback() method), if
  304. /// \c callback is non \c NULL then the callback function is called
  305. /// with the argument of a reference to the node and the given
  306. /// callback argument (\c callback_arg). The template parameter specifies
  307. /// the type of the callback argument.
  308. /// The callback function returns either \c true or \c false, meaning
  309. /// the search should stop or continue, respectively.
  310. /// If the return value is \c true the search stops immediately at the
  311. /// node even if there could be a longer matching name below it.
  312. /// In reality, this convoluted callback rule is specifically intended
  313. /// to be used to handle a zone cut (delegation) at a name search inside
  314. /// a zone, and won't be used in any other cases.
  315. /// Other applications of the tree won't need callbacks, and they should
  316. /// use the non templated version of the \c find() method.
  317. ///
  318. /// Since the expected usage of callback is very limited, we do not
  319. /// generalize the interface so that it can be an arbitrary functions or
  320. /// functor objects in favor of simplicity and efficiency.
  321. ///
  322. /// This method involves operations on names that can throw an exception.
  323. /// If that happens the exception will be propagated to the caller.
  324. /// The callback function should generally not throw an exception, but
  325. /// if it throws, the exception will be propagated to the caller.
  326. ///
  327. /// \param name Target to be found
  328. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  329. /// it will store a pointer to the matching node
  330. /// \param callback If non \c NULL, a call back function to be called
  331. /// at "delegation" nodes (see above).
  332. /// \param callback_arg A caller supplied argument to be passed to
  333. /// \c callback.
  334. ///
  335. /// \return \c EXACTMATCH A node that whose name is equal to \c name is
  336. /// found. \c *node will be set to point to that node.
  337. /// \return \c PARTIALMATCH There is a no exact match, but a superdomain
  338. /// of \c name exists. \c node will be set to point to the node whose
  339. /// name is the longest among such superdomains.
  340. /// \return \c NOTFOUND There is no exact or partial match against \c name
  341. /// \c *node will be intact in this case.
  342. template <typename CBARG>
  343. Result find(const isc::dns::Name& name, RBNode<T>** node,
  344. bool (*callback)(const RBNode<T>&, CBARG),
  345. CBARG callback_arg) const;
  346. /// Same as the other version, but the returned \c node will be immutable.
  347. template <typename CBARG>
  348. Result find(const isc::dns::Name& name, const RBNode<T>** node,
  349. bool (*callback)(const RBNode<T>&, CBARG),
  350. CBARG callback_arg) const;
  351. /// Same as the templated version, but does not use callback.
  352. ///
  353. /// Applications except the zone implementation should generally use the
  354. /// non templated version.
  355. Result find(const isc::dns::Name& name, RBNode<T>** node) const {
  356. return (find<void*>(name, node, NULL, NULL));
  357. }
  358. /// Same as the templated version, but does not use callback, and the
  359. /// returned \c node will be immutable.
  360. ///
  361. /// In general, this version should be preferred over the other non
  362. /// templated version, unless the caller knows it should modify the
  363. /// returned node.
  364. Result find(const isc::dns::Name& name, const RBNode<T>** node) const {
  365. return (find<void*>(name, node, NULL, NULL));
  366. }
  367. /// \brief Get the total node count in the tree
  368. /// the node count including the node created common suffix node,
  369. /// this function will only be used for debuging
  370. int getNodeCount() const { return (node_count_);}
  371. //@}
  372. /// \name Debug function
  373. //@{
  374. /// \brief print the nodes in the trees
  375. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  376. //@}
  377. /// \name Modify function
  378. //@{
  379. /// \brief Insert the domain name into the tree
  380. /// \param name The name to be inserted into the tree
  381. /// \param inserted_node If no node with the name in the tree,
  382. /// new \c RBNode will be created, otherwise nothing will be done.
  383. /// Anyway the pointer point to the node with the name will be assigned to
  384. /// inserted_node
  385. /// \return
  386. // - SUCCESS means no node exists in the tree with the name before insert
  387. /// - ALREADYEXISTS means already has the node with the given name
  388. //
  389. /// \node To modify the data related with one name but not sure the name has
  390. /// inserted or not, it is better to call \c insert,instead of
  391. /// \c find(), in case the name isn't exist and needs to insert again
  392. Result insert(const isc::dns::Name& name, RBNode<T>** inserted_node);
  393. //@}
  394. /// \brief Swaps two tree's contents.
  395. ///
  396. /// This acts the same as many std::*.swap functions, exchanges the
  397. /// contents. This doesn't throw anything.
  398. void swap(RBTree<T>& other) {
  399. std::swap(root_, other.root_);
  400. std::swap(NULLNODE, other.NULLNODE);
  401. std::swap(node_count_, other.node_count_);
  402. }
  403. private:
  404. /// \name RBTree balance functions
  405. //@{
  406. void insertRebalance(RBNode<T>** root, RBNode<T>* node);
  407. RBNode<T>* rightRotate(RBNode<T>** root, RBNode<T>* node);
  408. RBNode<T>* leftRotate(RBNode<T>** root, RBNode<T>* node);
  409. //@}
  410. /// \name Helper functions
  411. //@{
  412. /// \brief delete tree whose root is equal to node
  413. void deleteHelper(RBNode<T> *node);
  414. /// \brief find the node with name
  415. /// \param name is the target, up will points to the base domain of
  416. /// the tree which name resides, node will point to the target node
  417. /// if we has exact same name or partical name in current tree.
  418. /// so for example, in zone a, we has
  419. /// b.a, c.b.a and d.b.a search c.b.a, up will points to b.a.
  420. /// and node will points to c.b.a
  421. /// \note parameter up now is not used by any funciton, but we are gonna
  422. /// need it soon to implement function like remove
  423. template <typename CBARG>
  424. Result findHelper(const isc::dns::Name& name, const RBNode<T>** up,
  425. RBNode<T>** node,
  426. bool (*callback)(const RBNode<T>&, CBARG),
  427. CBARG callback_arg) const;
  428. void dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  429. unsigned int depth) const;
  430. /// for indent purpose, add certian mount empty charachter to output stream
  431. /// according to the depth. This is a helper function which is only used when
  432. /// dump tree
  433. static void indent(std::ostream& os, unsigned int depth);
  434. /// Split one node into two nodes, keep the old node and create one new
  435. /// node, old node will hold the base name, new node will be the down node
  436. /// of old node, new node will hold the sub_name, the data
  437. /// of old node will be move into new node, and old node became non-terminal
  438. void nodeFission(RBNode<T>& node, const isc::dns::Name& sub_name);
  439. //@}
  440. RBNode<T>* root_;
  441. RBNode<T>* NULLNODE;
  442. /// the node count of current tree
  443. unsigned int node_count_;
  444. };
  445. template <typename T>
  446. RBTree<T>::RBTree() {
  447. NULLNODE = RBNode<T>::NULL_NODE();
  448. root_ = NULLNODE;
  449. node_count_ = 0;
  450. }
  451. template <typename T>
  452. RBTree<T>::~RBTree() {
  453. deleteHelper(root_);
  454. assert(node_count_ == 0);
  455. }
  456. template <typename T>
  457. void RBTree<T> ::deleteHelper(RBNode<T> *root) {
  458. if (root == NULLNODE) {
  459. return;
  460. }
  461. RBNode<T> *node = root;
  462. while (root->left_ != NULLNODE || root->right_ != NULLNODE) {
  463. while (node->left_ != NULLNODE || node->right_ != NULLNODE) {
  464. node = (node->left_ != NULLNODE) ? node->left_ : node->right_;
  465. }
  466. RBNode<T> *parent = node->parent_;
  467. if (parent->left_ == node) {
  468. parent->left_ = NULLNODE;
  469. } else {
  470. parent->right_ = NULLNODE;
  471. }
  472. deleteHelper(node->down_);
  473. delete node;
  474. --node_count_;
  475. node = parent;
  476. }
  477. deleteHelper(root->down_);
  478. delete root;
  479. --node_count_;
  480. }
  481. template <typename T> template <typename CBARG>
  482. typename RBTree<T>::Result
  483. RBTree<T>::find(const isc::dns::Name& name, RBNode<T>** node,
  484. bool (*callback)(const RBNode<T>&, CBARG),
  485. CBARG callback_arg) const
  486. {
  487. const RBNode<T>* up_node = NULLNODE;
  488. return (findHelper(name, &up_node, node, callback, callback_arg));
  489. }
  490. template <typename T> template <typename CBARG>
  491. typename RBTree<T>::Result
  492. RBTree<T>::find(const isc::dns::Name& name, const RBNode<T>** node,
  493. bool (*callback)(const RBNode<T>&, CBARG),
  494. CBARG callback_arg) const
  495. {
  496. const RBNode<T>* up_node;
  497. RBNode<T>* target_node;
  498. const typename RBTree<T>::Result ret =
  499. findHelper(name, &up_node, &target_node, callback, callback_arg);
  500. if (ret != NOTFOUND) {
  501. *node = target_node;
  502. }
  503. return (ret);
  504. }
  505. template <typename T> template <typename CBARG>
  506. typename RBTree<T>::Result
  507. RBTree<T>::findHelper(const isc::dns::Name& target_name,
  508. const RBNode<T>** up_node,
  509. RBNode<T>** target,
  510. bool (*callback)(const RBNode<T>&, CBARG),
  511. CBARG callback_arg) const
  512. {
  513. using namespace helper;
  514. RBNode<T>* node = root_;
  515. typename RBTree<T>::Result ret = NOTFOUND;
  516. *up_node = NULLNODE;
  517. isc::dns::Name name = target_name;
  518. while (node != NULLNODE) {
  519. const isc::dns::NameComparisonResult compare_result =
  520. name.compare(node->name_);
  521. const isc::dns::NameComparisonResult::NameRelation relation =
  522. compare_result.getRelation();
  523. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  524. if (!node->isEmpty()) {
  525. *target = node;
  526. ret = EXACTMATCH;
  527. }
  528. break;
  529. } else {
  530. const int common_label_count = compare_result.getCommonLabels();
  531. // If the common label count is 1, there is no common label between
  532. // the two names, except the trailing "dot".
  533. if (common_label_count == 1) {
  534. node = (compare_result.getOrder() < 0) ?
  535. node->left_ : node->right_;
  536. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  537. if (!node->isEmpty()) {
  538. ret = RBTree<T>::PARTIALMATCH;
  539. *target = node;
  540. if (callback != NULL && node->callback_required_) {
  541. if ((callback)(*node, callback_arg)) {
  542. break;
  543. }
  544. }
  545. }
  546. *up_node = node;
  547. name = name - node->name_;
  548. node = node->down_;
  549. } else {
  550. break;
  551. }
  552. }
  553. }
  554. return (ret);
  555. }
  556. template <typename T>
  557. typename RBTree<T>::Result
  558. RBTree<T>::insert(const isc::dns::Name& target_name, RBNode<T>** new_node) {
  559. using namespace helper;
  560. RBNode<T>* parent = NULLNODE;
  561. RBNode<T>* current = root_;
  562. RBNode<T>* up_node = NULLNODE;
  563. isc::dns::Name name = target_name;
  564. int order = -1;
  565. while (current != NULLNODE) {
  566. const isc::dns::NameComparisonResult compare_result =
  567. name.compare(current->name_);
  568. const isc::dns::NameComparisonResult::NameRelation relation =
  569. compare_result.getRelation();
  570. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  571. if (new_node != NULL) {
  572. *new_node = current;
  573. }
  574. return (ALREADYEXISTS);
  575. } else {
  576. const int common_label_count = compare_result.getCommonLabels();
  577. if (common_label_count == 1) {
  578. parent = current;
  579. order = compare_result.getOrder();
  580. current = order < 0 ? current->left_ : current->right_;
  581. } else {
  582. // insert sub domain to sub tree
  583. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  584. parent = NULLNODE;
  585. up_node = current;
  586. name = name - current->name_;
  587. current = current->down_;
  588. } else {
  589. // The number of labels in common is fewer
  590. // than the number of labels at the current
  591. // node, so the current node must be adjusted
  592. // to have just the common suffix, and a down
  593. // pointer made to a new tree.
  594. const isc::dns::Name common_ancestor = name.split(
  595. name.getLabelCount() - common_label_count,
  596. common_label_count);
  597. nodeFission(*current, common_ancestor);
  598. }
  599. }
  600. }
  601. }
  602. RBNode<T>** current_root = (up_node != NULLNODE) ?
  603. &(up_node->down_) : &root_;
  604. // using auto_ptr here is avoid memory leak in case of exceptoin raised
  605. // after the RBNode creation, if we can make sure no exception will be
  606. // raised until the end of the function, we can remove it for optimization
  607. std::auto_ptr<RBNode<T> > node(new RBNode<T>(name));
  608. node->parent_ = parent;
  609. if (parent == NULLNODE) {
  610. *current_root = node.get();
  611. //node is the new root of sub tree, so its init color
  612. // is BLACK
  613. node->color_ = RBNode<T>::BLACK;
  614. } else if (order < 0) {
  615. parent->left_ = node.get();
  616. } else {
  617. parent->right_ = node.get();
  618. }
  619. insertRebalance(current_root, node.get());
  620. if (new_node != NULL) {
  621. *new_node = node.get();
  622. }
  623. ++node_count_;
  624. node.release();
  625. return (SUCCESS);
  626. }
  627. template <typename T>
  628. void
  629. RBTree<T>::nodeFission(RBNode<T>& node, const isc::dns::Name& base_name) {
  630. using namespace helper;
  631. const isc::dns::Name sub_name = node.name_ - base_name;
  632. // using auto_ptr here is to avoid memory leak in case of exceptoin raised
  633. // after the RBNode creation
  634. std::auto_ptr<RBNode<T> > down_node(new RBNode<T>(sub_name));
  635. std::swap(node.data_, down_node->data_);
  636. std::swap(node.callback_required_, down_node->callback_required_);
  637. down_node->down_ = node.down_;
  638. node.name_ = base_name;
  639. node.down_ = down_node.get();
  640. //root node of sub tree, the initial color is BLACK
  641. down_node->color_ = RBNode<T>::BLACK;
  642. ++node_count_;
  643. down_node.release();
  644. }
  645. template <typename T>
  646. void
  647. RBTree<T>::insertRebalance(RBNode<T>** root, RBNode<T>* node) {
  648. RBNode<T>* uncle;
  649. while (node != *root && node->parent_->color_ == RBNode<T>::RED) {
  650. if (node->parent_ == node->parent_->parent_->left_) {
  651. uncle = node->parent_->parent_->right_;
  652. if (uncle->color_ == RBNode<T>::RED) {
  653. node->parent_->color_ = RBNode<T>::BLACK;
  654. uncle->color_ = RBNode<T>::BLACK;
  655. node->parent_->parent_->color_ = RBNode<T>::RED;
  656. node = node->parent_->parent_;
  657. } else {
  658. if (node == node->parent_->right_) {
  659. node = node->parent_;
  660. leftRotate(root, node);
  661. }
  662. node->parent_->color_ = RBNode<T>::BLACK;
  663. node->parent_->parent_->color_ = RBNode<T>::RED;
  664. rightRotate(root, node->parent_->parent_);
  665. }
  666. } else {
  667. uncle = node->parent_->parent_->left_;
  668. if (uncle->color_ == RBNode<T>::RED) {
  669. node->parent_->color_ = RBNode<T>::BLACK;
  670. uncle->color_ = RBNode<T>::BLACK;
  671. node->parent_->parent_->color_ = RBNode<T>::RED;
  672. node = node->parent_->parent_;
  673. } else {
  674. if (node == node->parent_->left_) {
  675. node = node->parent_;
  676. rightRotate(root, node);
  677. }
  678. node->parent_->color_ = RBNode<T>::BLACK;
  679. node->parent_->parent_->color_ = RBNode<T>::RED;
  680. leftRotate(root, node->parent_->parent_);
  681. }
  682. }
  683. }
  684. (*root)->color_ = RBNode<T>::BLACK;
  685. }
  686. template <typename T>
  687. RBNode<T>*
  688. RBTree<T>::leftRotate(RBNode<T>** root, RBNode<T>* node) {
  689. RBNode<T>* right = node->right_;
  690. node->right_ = right->left_;
  691. if (right->left_ != NULLNODE)
  692. right->left_->parent_ = node;
  693. right->parent_ = node->parent_;
  694. if (node->parent_ != NULLNODE) {
  695. if (node == node->parent_->left_) {
  696. node->parent_->left_ = right;
  697. } else {
  698. node->parent_->right_ = right;
  699. }
  700. } else {
  701. *root = right;
  702. }
  703. right->left_ = node;
  704. node->parent_ = right;
  705. return (node);
  706. }
  707. template <typename T>
  708. RBNode<T>*
  709. RBTree<T>::rightRotate(RBNode<T>** root, RBNode<T>* node) {
  710. RBNode<T>* left = node->left_;
  711. node->left_ = left->right_;
  712. if (left->right_ != NULLNODE)
  713. left->right_->parent_ = node;
  714. left->parent_ = node->parent_;
  715. if (node->parent_ != NULLNODE) {
  716. if (node == node->parent_->right_) {
  717. node->parent_->right_ = left;
  718. } else {
  719. node->parent_->left_ = left;
  720. }
  721. } else {
  722. *root = left;
  723. }
  724. left->right_ = node;
  725. node->parent_ = left;
  726. return (node);
  727. }
  728. template <typename T>
  729. void
  730. RBTree<T>::dumpTree(std::ostream& os, unsigned int depth) const {
  731. indent(os, depth);
  732. os << "tree has " << node_count_ << " node(s)\n";
  733. dumpTreeHelper(os, root_, depth);
  734. }
  735. template <typename T>
  736. void
  737. RBTree<T>::dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  738. unsigned int depth) const
  739. {
  740. if (node == NULLNODE) {
  741. indent(os, depth);
  742. os << "NULL\n";
  743. return;
  744. }
  745. indent(os, depth);
  746. os << node->name_.toText() << " ("
  747. << ((node->color_ == RBNode<T>::BLACK) ? "black" : "red") << ")";
  748. os << ((node->isEmpty()) ? "[invisible] \n" : "\n");
  749. if (node->down_ != NULLNODE) {
  750. indent(os, depth + 1);
  751. os << "begin down from " << node->name_.toText() << "\n";
  752. dumpTreeHelper(os, node->down_, depth + 1);
  753. indent(os, depth + 1);
  754. os << "end down from " << node->name_.toText() << "\n";
  755. }
  756. dumpTreeHelper(os, node->left_, depth + 1);
  757. dumpTreeHelper(os, node->right_, depth + 1);
  758. }
  759. template <typename T>
  760. void
  761. RBTree<T>::indent(std::ostream& os, unsigned int depth) {
  762. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  763. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  764. }
  765. }
  766. }
  767. #endif // _RBTREE_H
  768. // Local Variables:
  769. // mode: c++
  770. // End: