|
12 | 12 | //! trees. The only requirement for the types is that the key implements
|
13 | 13 | //! `TotalOrd`.
|
14 | 14 |
|
15 |
| - |
16 | 15 | use std::util::{swap, replace};
|
17 | 16 | use std::iter::{Peekable};
|
18 | 17 | use std::cmp::Ordering;
|
| 18 | +use std::ptr; |
19 | 19 |
|
20 | 20 | // This is implemented as an AA tree, which is a simplified variation of
|
21 | 21 | // a red-black tree where red (horizontal) nodes can only be added
|
@@ -157,6 +157,23 @@ impl<K: TotalOrd, V> TreeMap<K, V> {
|
157 | 157 | TreeMapRevIterator{iter: self.iter()}
|
158 | 158 | }
|
159 | 159 |
|
| 160 | + /// Get a lazy forward iterator over the key-value pairs in the |
| 161 | + /// map, with the values being mutable. |
| 162 | + pub fn mut_iter<'a>(&'a mut self) -> TreeMapMutIterator<'a, K, V> { |
| 163 | + TreeMapMutIterator { |
| 164 | + stack: ~[], |
| 165 | + node: mut_deref(&mut self.root), |
| 166 | + remaining_min: self.length, |
| 167 | + remaining_max: self.length |
| 168 | + } |
| 169 | + } |
| 170 | + /// Get a lazy reverse iterator over the key-value pairs in the |
| 171 | + /// map, with the values being mutable. |
| 172 | + pub fn mut_rev_iter<'a>(&'a mut self) -> TreeMapMutRevIterator<'a, K, V> { |
| 173 | + TreeMapMutRevIterator{iter: self.mut_iter()} |
| 174 | + } |
| 175 | + |
| 176 | + |
160 | 177 | /// Get a lazy iterator that should be initialized using
|
161 | 178 | /// `iter_traverse_left`/`iter_traverse_right`/`iter_traverse_complete`.
|
162 | 179 | fn iter_for_traversal<'a>(&'a self) -> TreeMapIterator<'a, K, V> {
|
@@ -212,6 +229,63 @@ impl<K: TotalOrd, V> TreeMap<K, V> {
|
212 | 229 | }
|
213 | 230 | }
|
214 | 231 | }
|
| 232 | + /// Get a lazy iterator that should be initialized using |
| 233 | + /// `mut_iter_traverse_left`/`mut_iter_traverse_right`/`mut_iter_traverse_complete`. |
| 234 | + fn mut_iter_for_traversal<'a>(&'a mut self) -> TreeMapMutIterator<'a, K, V> { |
| 235 | + TreeMapMutIterator { |
| 236 | + stack: ~[], |
| 237 | + node: mut_deref(&mut self.root), |
| 238 | + remaining_min: 0, |
| 239 | + remaining_max: self.length |
| 240 | + } |
| 241 | + } |
| 242 | + |
| 243 | + /// Return a lazy value iterator to the first key-value pair (with |
| 244 | + /// the value being mutable) whose key is not less than `k`. |
| 245 | + /// |
| 246 | + /// If all keys in map are less than `k` an empty iterator is |
| 247 | + /// returned. |
| 248 | + pub fn mut_lower_bound<'a>(&'a mut self, k: &K) -> TreeMapMutIterator<'a, K, V> { |
| 249 | + let mut iter = self.mut_iter_for_traversal(); |
| 250 | + loop { |
| 251 | + if !iter.node.is_null() { |
| 252 | + let node_k = unsafe {&(*iter.node).key}; |
| 253 | + match k.cmp(node_k) { |
| 254 | + Less => mut_iter_traverse_left(&mut iter), |
| 255 | + Greater => mut_iter_traverse_right(&mut iter), |
| 256 | + Equal => { |
| 257 | + mut_iter_traverse_complete(&mut iter); |
| 258 | + return iter; |
| 259 | + } |
| 260 | + } |
| 261 | + } else { |
| 262 | + mut_iter_traverse_complete(&mut iter); |
| 263 | + return iter; |
| 264 | + } |
| 265 | + } |
| 266 | + } |
| 267 | + |
| 268 | + /// Return a lazy iterator to the first key-value pair (with the |
| 269 | + /// value being mutable) whose key is greater than `k`. |
| 270 | + /// |
| 271 | + /// If all keys in map are not greater than `k` an empty iterator |
| 272 | + /// is returned. |
| 273 | + pub fn mut_upper_bound<'a>(&'a mut self, k: &K) -> TreeMapMutIterator<'a, K, V> { |
| 274 | + let mut iter = self.mut_iter_for_traversal(); |
| 275 | + loop { |
| 276 | + if !iter.node.is_null() { |
| 277 | + let node_k = unsafe {&(*iter.node).key}; |
| 278 | + match k.cmp(node_k) { |
| 279 | + Less => mut_iter_traverse_left(&mut iter), |
| 280 | + Greater => mut_iter_traverse_right(&mut iter), |
| 281 | + Equal => mut_iter_traverse_right(&mut iter) |
| 282 | + } |
| 283 | + } else { |
| 284 | + mut_iter_traverse_complete(&mut iter); |
| 285 | + return iter; |
| 286 | + } |
| 287 | + } |
| 288 | + } |
215 | 289 |
|
216 | 290 | /// Get a lazy iterator that consumes the treemap.
|
217 | 291 | pub fn move_iter(self) -> TreeMapMoveIterator<K, V> {
|
@@ -340,6 +414,146 @@ fn iter_traverse_complete<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) {
|
340 | 414 | }
|
341 | 415 | }
|
342 | 416 |
|
| 417 | + |
| 418 | +fn mut_deref<K, V>(x: &mut Option<~TreeNode<K, V>>) -> *mut TreeNode<K, V> { |
| 419 | + match *x { |
| 420 | + Some(ref mut n) => { |
| 421 | + let n: &mut TreeNode<K, V> = *n; |
| 422 | + n as *mut TreeNode<K, V> |
| 423 | + } |
| 424 | + None => ptr::mut_null() |
| 425 | + } |
| 426 | +} |
| 427 | + |
| 428 | +/// Lazy forward iterator over a map that allows for the mutation of |
| 429 | +/// the values. |
| 430 | +pub struct TreeMapMutIterator<'a, K, V> { |
| 431 | + priv stack: ~[&'a mut TreeNode<K, V>], |
| 432 | + // Unfortunately, we require some unsafe-ness to get around the |
| 433 | + // fact that we would be storing a reference *into* one of the |
| 434 | + // nodes in the stack. |
| 435 | + // |
| 436 | + // As far as the compiler knows, this would let us invalidate the |
| 437 | + // reference by assigning a new value to this node's position in |
| 438 | + // its parent, which would cause this current one to be |
| 439 | + // deallocated so this reference would be invalid. (i.e. the |
| 440 | + // compilers complaints are 100% correct.) |
| 441 | + // |
| 442 | + // However, as far as you humans reading this code know (or are |
| 443 | + // about to know, if you haven't read far enough down yet), we are |
| 444 | + // only reading from the TreeNode.{left,right} fields. the only |
| 445 | + // thing that is ever mutated is the .value field (although any |
| 446 | + // actual mutation that happens is done externally, by the |
| 447 | + // iterator consumer). So, don't be so concerned, rustc, we've got |
| 448 | + // it under control. |
| 449 | + // |
| 450 | + // (This field can legitimately be null.) |
| 451 | + priv node: *mut TreeNode<K, V>, |
| 452 | + priv remaining_min: uint, |
| 453 | + priv remaining_max: uint |
| 454 | +} |
| 455 | + |
| 456 | +impl<'a, K, V> TreeMapMutIterator<'a, K, V> { |
| 457 | + #[inline(always)] |
| 458 | + fn next_(&mut self, forward: bool) -> Option<(&'a K, &'a mut V)> { |
| 459 | + while !self.stack.is_empty() || !self.node.is_null() { |
| 460 | + let node = self.node; |
| 461 | + if !node.is_null() { |
| 462 | + let node = unsafe {&mut *node}; |
| 463 | + { |
| 464 | + let next_node = if forward { &mut node.left } else { &mut node.right }; |
| 465 | + self.node = mut_deref(next_node); |
| 466 | + } |
| 467 | + self.stack.push(node); |
| 468 | + } else { |
| 469 | + let node = self.stack.pop(); |
| 470 | + self.node = mut_deref(if forward { &mut node.right } else { &mut node.left }); |
| 471 | + self.remaining_max -= 1; |
| 472 | + if self.remaining_min > 0 { |
| 473 | + self.remaining_min -= 1; |
| 474 | + } |
| 475 | + return Some((&node.key, &mut node.value)); |
| 476 | + } |
| 477 | + } |
| 478 | + None |
| 479 | + } |
| 480 | +} |
| 481 | + |
| 482 | +impl<'a, K, V> Iterator<(&'a K, &'a mut V)> for TreeMapMutIterator<'a, K, V> { |
| 483 | + /// Advance the iterator to the next node (in order) and return a |
| 484 | + /// tuple with a reference to the key and value. If there are no |
| 485 | + /// more nodes, return `None`. |
| 486 | + fn next(&mut self) -> Option<(&'a K, &'a mut V)> { |
| 487 | + self.next_(true) |
| 488 | + } |
| 489 | + |
| 490 | + #[inline] |
| 491 | + fn size_hint(&self) -> (uint, Option<uint>) { |
| 492 | + (self.remaining_min, Some(self.remaining_max)) |
| 493 | + } |
| 494 | +} |
| 495 | + |
| 496 | +/// Lazy backward iterator over a map |
| 497 | +pub struct TreeMapMutRevIterator<'a, K, V> { |
| 498 | + priv iter: TreeMapMutIterator<'a, K, V>, |
| 499 | +} |
| 500 | + |
| 501 | +impl<'a, K, V> Iterator<(&'a K, &'a mut V)> for TreeMapMutRevIterator<'a, K, V> { |
| 502 | + /// Advance the iterator to the next node (in order) and return a |
| 503 | + /// tuple with a reference to the key and value. If there are no |
| 504 | + /// more nodes, return `None`. |
| 505 | + fn next(&mut self) -> Option<(&'a K, &'a mut V)> { |
| 506 | + self.iter.next_(false) |
| 507 | + } |
| 508 | + |
| 509 | + #[inline] |
| 510 | + fn size_hint(&self) -> (uint, Option<uint>) { |
| 511 | + self.iter.size_hint() |
| 512 | + } |
| 513 | +} |
| 514 | + |
| 515 | +/// iter_traverse_left, iter_traverse_right and iter_traverse_complete are used to |
| 516 | +/// initialize TreeMapMutIterator pointing to element inside tree structure. |
| 517 | +/// |
| 518 | +/// They should be used in following manner: |
| 519 | +/// - create iterator using TreeMap::iter_for_traversal |
| 520 | +/// - find required node using `iter_traverse_left`/`iter_traverse_right` |
| 521 | +/// (current node is `TreeMapMutIterator::node` field) |
| 522 | +/// - complete initialization with `iter_traverse_complete` |
| 523 | +#[inline] |
| 524 | +fn mut_iter_traverse_left<'a, K, V>(it: &mut TreeMapMutIterator<'a, K, V>) { |
| 525 | + // guaranteed to be non-null |
| 526 | + let node = unsafe {&mut *it.node}; |
| 527 | + it.node = mut_deref(&mut node.left); |
| 528 | + it.stack.push(node); |
| 529 | +} |
| 530 | + |
| 531 | +#[inline] |
| 532 | +fn mut_iter_traverse_right<'a, K, V>(it: &mut TreeMapMutIterator<'a, K, V>) { |
| 533 | + // guaranteed to be non-null |
| 534 | + let node = unsafe {&mut *it.node}; |
| 535 | + it.node = mut_deref(&mut node.right); |
| 536 | +} |
| 537 | + |
| 538 | +/// iter_traverse_left, iter_traverse_right and iter_traverse_complete are used to |
| 539 | +/// initialize TreeMapMutIterator pointing to element inside tree structure. |
| 540 | +/// |
| 541 | +/// Completes traversal. Should be called before using iterator. |
| 542 | +/// Iteration will start from `self.node`. |
| 543 | +/// If `self.node` is None iteration will start from last node from which we |
| 544 | +/// traversed left. |
| 545 | +#[inline] |
| 546 | +fn mut_iter_traverse_complete<'a, K, V>(it: &mut TreeMapMutIterator<'a, K, V>) { |
| 547 | + if !it.node.is_null() { |
| 548 | + unsafe { |
| 549 | + it.stack.push(&mut *it.node); |
| 550 | + } |
| 551 | + it.node = ptr::mut_null(); |
| 552 | + } |
| 553 | +} |
| 554 | + |
| 555 | + |
| 556 | + |
343 | 557 | /// Lazy forward iterator over a map that consumes the map while iterating
|
344 | 558 | pub struct TreeMapMoveIterator<K, V> {
|
345 | 559 | priv stack: ~[TreeNode<K, V>],
|
@@ -1129,6 +1343,69 @@ mod test_treemap {
|
1129 | 1343 | }
|
1130 | 1344 | }
|
1131 | 1345 |
|
| 1346 | + #[test] |
| 1347 | + fn test_mut_iter() { |
| 1348 | + let mut m = TreeMap::new(); |
| 1349 | + for i in range(0u, 10) { |
| 1350 | + assert!(m.insert(i, 100 * i)); |
| 1351 | + } |
| 1352 | + |
| 1353 | + for (i, (&k, v)) in m.mut_iter().enumerate() { |
| 1354 | + *v += k * 10 + i; // 000 + 00 + 0, 100 + 10 + 1, ... |
| 1355 | + } |
| 1356 | + |
| 1357 | + for (&k, &v) in m.iter() { |
| 1358 | + assert_eq!(v, 111 * k); |
| 1359 | + } |
| 1360 | + } |
| 1361 | + #[test] |
| 1362 | + fn test_mut_rev_iter() { |
| 1363 | + let mut m = TreeMap::new(); |
| 1364 | + for i in range(0u, 10) { |
| 1365 | + assert!(m.insert(i, 100 * i)); |
| 1366 | + } |
| 1367 | + |
| 1368 | + for (i, (&k, v)) in m.mut_rev_iter().enumerate() { |
| 1369 | + *v += k * 10 + (9 - i); // 900 + 90 + (9 - 0), 800 + 80 + (9 - 1), ... |
| 1370 | + } |
| 1371 | + |
| 1372 | + for (&k, &v) in m.iter() { |
| 1373 | + assert_eq!(v, 111 * k); |
| 1374 | + } |
| 1375 | + } |
| 1376 | + |
| 1377 | + #[test] |
| 1378 | + fn test_mut_interval_iter() { |
| 1379 | + let mut m_lower = TreeMap::new(); |
| 1380 | + let mut m_upper = TreeMap::new(); |
| 1381 | + for i in range(1, 100) { |
| 1382 | + assert!(m_lower.insert(i * 2, i * 4)); |
| 1383 | + assert!(m_upper.insert(i * 2, i * 4)); |
| 1384 | + } |
| 1385 | + |
| 1386 | + for i in range(1, 199) { |
| 1387 | + let mut lb_it = m_lower.mut_lower_bound(&i); |
| 1388 | + let (&k, v) = lb_it.next().unwrap(); |
| 1389 | + let lb = i + i % 2; |
| 1390 | + assert_eq!(lb, k); |
| 1391 | + *v -= k; |
| 1392 | + } |
| 1393 | + for i in range(0, 198) { |
| 1394 | + let mut ub_it = m_upper.mut_upper_bound(&i); |
| 1395 | + let (&k, v) = ub_it.next().unwrap(); |
| 1396 | + let ub = i + 2 - i % 2; |
| 1397 | + assert_eq!(ub, k); |
| 1398 | + *v -= k; |
| 1399 | + } |
| 1400 | + |
| 1401 | + assert!(m_lower.mut_lower_bound(&199).next().is_none()); |
| 1402 | + |
| 1403 | + assert!(m_upper.mut_upper_bound(&198).next().is_none()); |
| 1404 | + |
| 1405 | + assert!(m_lower.iter().all(|(_, &x)| x == 0)); |
| 1406 | + assert!(m_upper.iter().all(|(_, &x)| x == 0)); |
| 1407 | + } |
| 1408 | + |
1132 | 1409 | #[test]
|
1133 | 1410 | fn test_eq() {
|
1134 | 1411 | let mut a = TreeMap::new();
|
|
0 commit comments