rbtree.h 65 KB

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