rbtree.h 69 KB

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