rbtree.h 53 KB

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