Skip to content

Commit 746dd8b

Browse files
committed
Add usage example for the interval tree.
Signed-off-by: Liu Jiang <gerry@linux.alibaba.com>
1 parent c4eeebc commit 746dd8b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/interval_tree.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,36 @@
55
//!
66
//! It's not designed as a generic interval tree, but specialized for VMM resource management.
77
//! In addition to the normal get/insert/delete/update operations, it also implements allocate/free.
8+
//!
9+
//! # Examples
10+
//! ```rust
11+
//! extern crate vm_allocator;
12+
//! use vm_allocator::{IntervalTree, Range, Constraint};
13+
//!
14+
//! // Create an interval tree and add availale resources into it.
15+
//! let mut tree = IntervalTree::<u64>::new();
16+
//! tree.insert(Range::new(0x100, 0x100), None);
17+
//! tree.insert(Range::new(0x200, 0x2ff), None);
18+
//!
19+
//! // Allocate a range with constraints.
20+
//! let mut constraint = Constraint::new(8);
21+
//! constraint.min = 0x211;
22+
//! constraint.max = 0x21f;
23+
//! constraint.align = 0x8;
24+
//!
25+
//! let key = tree.allocate(&constraint);
26+
//! assert_eq!(key, Some(Range::new(0x218, 0x21f)));
27+
//!
28+
//! // Associate data with the allocated range and mark the range as occupied.
29+
//! // Note: caller needs to protect from concurrent access between allocate() and the first call
30+
//! // to update() to mark range as occupied.
31+
//! let old = tree.update(&Range::new(0x218, 0x21f), 2);
32+
//! assert_eq!(old, None);
33+
//! let old = tree.update(&Range::new(0x218, 0x21f), 3);
34+
//! assert_eq!(old, Some(2));
35+
//! let val = tree.get(&Range::new(0x218, 0x21f));
36+
//! assert_eq!(val, Some(Some(&3)));
37+
//! ```
838
939
use crate::{AllocPolicy, Constraint};
1040
use std::cmp::{max, min, Ordering};

0 commit comments

Comments
 (0)