Documentation/core-api/rbtree.rst

Source file repositories/reference/linux-study-clean/Documentation/core-api/rbtree.rst

File Facts

System
Linux kernel
Corpus path
Documentation/core-api/rbtree.rst
Extension
.rst
Size
15166 bytes
Lines
430
Domain
Support Tooling And Documentation
Bucket
Documentation
Inferred role
Support Tooling And Documentation: documentation
Status
atlas-only

Why This File Exists

Repository support layer: documentation, build tooling, samples, user-space helper tools, generated initramfs support, licenses, and validation utilities.

Dependency Surface

Detected Declarations

Annotated Snippet

struct mytype {
  	struct rb_node node;
  	char *keystring;
  };

When dealing with a pointer to the embedded struct rb_node, the containing data
structure may be accessed with the standard container_of() macro.  In addition,
individual members may be accessed directly via rb_entry(node, type, member).

At the root of each rbtree is an rb_root structure, which is initialized to be
empty via:

  struct rb_root mytree = RB_ROOT;

Searching for a value in an rbtree
----------------------------------

Writing a search function for your tree is fairly straightforward: start at the
root, compare each value, and follow the left or right branch as necessary.

Example::

  struct mytype *my_search(struct rb_root *root, char *string)
  {
  	struct rb_node *node = root->rb_node;

  	while (node) {
  		struct mytype *data = container_of(node, struct mytype, node);
		int result;

		result = strcmp(string, data->keystring);

		if (result < 0)
  			node = node->rb_left;
		else if (result > 0)
  			node = node->rb_right;
		else
  			return data;
	}
	return NULL;
  }

Inserting data into an rbtree
-----------------------------

Inserting data in the tree involves first searching for the place to insert the
new node, then inserting the node and rebalancing ("recoloring") the tree.

The search for insertion differs from the previous search by finding the
location of the pointer on which to graft the new node.  The new node also
needs a link to its parent node for rebalancing purposes.

Example::

  int my_insert(struct rb_root *root, struct mytype *data)
  {
  	struct rb_node **new = &(root->rb_node), *parent = NULL;

  	/* Figure out where to put new node */
  	while (*new) {
  		struct mytype *this = container_of(*new, struct mytype, node);
  		int result = strcmp(data->keystring, this->keystring);

		parent = *new;
  		if (result < 0)
  			new = &((*new)->rb_left);
  		else if (result > 0)
  			new = &((*new)->rb_right);
  		else
  			return FALSE;

Annotation

Implementation Notes