rbtree.h 59 KB

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