rbtree.h 75 KB

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