Struct truck_topology::Wire
source · pub struct Wire<P, C> { /* private fields */ }
Expand description
Wire, a path or cycle which consists some edges.
The entity of this struct is VecDeque<Edge>
and almost methods are inherited from
VecDeque<Edge>
by Deref
and DerefMut
traits.
Implementations§
source§impl<P, C> Wire<P, C>
impl<P, C> Wire<P, C>
sourcepub fn new() -> Wire<P, C>
pub fn new() -> Wire<P, C>
Creates the empty wire.
Examples found in repository?
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
pub fn glue_at_boundaries(&self, other: &Self) -> Option<Self>
where
S: Clone + PartialEq,
Wire<P, C>: Debug, {
let surface = self.get_surface();
if surface != other.get_surface() || self.orientation() != other.orientation() {
return None;
}
let mut vemap: HashMap<VertexID<P>, &Edge<P, C>> = self
.absolute_boundaries()
.iter()
.flatten()
.map(|edge| (edge.front().id(), edge))
.collect();
other
.absolute_boundaries()
.iter()
.flatten()
.try_for_each(|edge| {
if let Some(edge0) = vemap.get(&edge.back().id()) {
if edge.front() == edge0.back() {
if edge.is_same(edge0) {
vemap.remove(&edge.back().id());
return Some(());
} else {
return None;
}
}
}
vemap.insert(edge.front().id(), edge);
Some(())
})?;
if vemap.is_empty() {
return None;
}
let mut boundaries = Vec::new();
while !vemap.is_empty() {
let mut wire = Wire::new();
let v = *vemap.iter().next().unwrap().0;
let mut edge = vemap.remove(&v).unwrap();
wire.push_back(edge.clone());
while let Some(edge0) = vemap.remove(&edge.back().id()) {
wire.push_back(edge0.clone());
edge = edge0;
}
boundaries.push(wire);
}
debug_assert!(Face::try_new(boundaries.clone(), ()).is_ok());
Some(Face {
boundaries,
orientation: self.orientation(),
surface: Arc::new(Mutex::new(surface)),
})
}
sourcepub fn with_capacity(capacity: usize) -> Wire<P, C>
pub fn with_capacity(capacity: usize) -> Wire<P, C>
Creates the empty wire with space for at least capacity
edges.
sourcepub fn edge_iter(&self) -> EdgeIter<'_, P, C>
pub fn edge_iter(&self) -> EdgeIter<'_, P, C>
Returns an iterator over the edges. Practically, an alias of iter()
.
Examples found in repository?
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
pub fn vertex_iter(&self) -> VertexIter<'_, P, C> {
VertexIter {
edge_iter: self.edge_iter().peekable(),
unconti_next: None,
cyclic: self.is_cyclic(),
}
}
/// Returns the front edge. If `self` is empty wire, returns None.
/// Practically, an alias of the inherited method `VecDeque::front()`.
#[inline(always)]
pub fn front_edge(&self) -> Option<&Edge<P, C>> { self.front() }
/// Returns the front vertex. If `self` is empty wire, returns None.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let mut wire = Wire::new();
/// assert_eq!(wire.front_vertex(), None);
/// wire.push_back(Edge::new(&v[1], &v[2], ()));
/// wire.push_front(Edge::new(&v[0], &v[1], ()));
/// assert_eq!(wire.front_vertex(), Some(&v[0]));
/// ```
#[inline(always)]
pub fn front_vertex(&self) -> Option<&Vertex<P>> { self.front().map(|edge| edge.front()) }
/// Returns the back edge. If `self` is empty wire, returns None.
/// Practically, an alias of the inherited method `VecDeque::back()`
#[inline(always)]
pub fn back_edge(&self) -> Option<&Edge<P, C>> { self.back() }
/// Returns the back edge. If `self` is empty wire, returns None.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let mut wire = Wire::new();
/// assert_eq!(wire.back_vertex(), None);
/// wire.push_back(Edge::new(&v[1], &v[2], ()));
/// wire.push_front(Edge::new(&v[0], &v[1], ()));
/// assert_eq!(wire.back_vertex(), Some(&v[2]));
/// ```
#[inline(always)]
pub fn back_vertex(&self) -> Option<&Vertex<P>> { self.back().map(|edge| edge.back()) }
/// Returns vertices at both ends.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 3]);
/// let mut wire = Wire::new();
/// assert_eq!(wire.back_vertex(), None);
/// wire.push_back(Edge::new(&v[1], &v[2], ()));
/// wire.push_front(Edge::new(&v[0], &v[1], ()));
/// assert_eq!(wire.ends_vertices(), Some((&v[0], &v[2])));
/// ```
#[inline(always)]
pub fn ends_vertices(&self) -> Option<(&Vertex<P>, &Vertex<P>)> {
match (self.front_vertex(), self.back_vertex()) {
(Some(got0), Some(got1)) => Some((got0, got1)),
_ => None,
}
}
/// Moves all the faces of `other` into `self`, leaving `other` empty.
#[inline(always)]
pub fn append(&mut self, other: &mut Wire<P, C>) { self.edge_list.append(&mut other.edge_list) }
/// Splits the `Wire` into two at the given index.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 7]);
/// let mut wire = Wire::new();
/// for i in 0..6 {
/// wire.push_back(Edge::new(&v[i], &v[i + 1], ()));
/// }
/// let original_wire = wire.clone();
/// let mut wire1 = wire.split_off(4);
/// assert_eq!(wire.len(), 4);
/// assert_eq!(wire1.len(), 2);
/// wire.append(&mut wire1);
/// assert_eq!(original_wire, wire);
/// ```
/// # Panics
/// Panics if `at > self.len()`
#[inline(always)]
pub fn split_off(&mut self, at: usize) -> Wire<P, C> {
Wire {
edge_list: self.edge_list.split_off(at),
}
}
/// Inverts the wire.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[3], &v[2], ()),
/// Edge::new(&v[2], &v[1], ()),
/// Edge::new(&v[1], &v[0], ()),
/// ]);
/// wire.invert();
/// for (i, vert) in wire.vertex_iter().enumerate() {
/// assert_eq!(v[i], vert);
/// }
/// ```
#[inline(always)]
pub fn invert(&mut self) -> &mut Self {
*self = self.inverse();
self
}
/// Returns the inverse wire.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[3], &v[2], ()),
/// Edge::new(&v[2], &v[1], ()),
/// Edge::new(&v[1], &v[0], ()),
/// ]);
/// let inverse = wire.inverse();
/// wire.invert();
/// for (edge0, edge1) in wire.edge_iter().zip(inverse.edge_iter()) {
/// assert_eq!(edge0, edge1);
/// }
/// ```
#[inline(always)]
pub fn inverse(&self) -> Wire<P, C> {
let edge_list = self.edge_iter().rev().map(|edge| edge.inverse()).collect();
Wire { edge_list }
}
/// Returns whether all the adjacent pairs of edges have shared vertices or not.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// ]);
/// assert!(!wire.is_continuous());
/// wire.insert(1, Edge::new(&v[1], &v[2], ()));
/// assert!(wire.is_continuous());
/// ```
/// ```
/// use truck_topology::*;
/// // The empty wire is continuous
/// assert!(Wire::<(), ()>::new().is_continuous());
/// ```
pub fn is_continuous(&self) -> bool {
let mut iter = self.edge_iter();
if let Some(edge) = iter.next() {
let mut prev = edge.back();
for edge in iter {
if prev != edge.front() {
return false;
}
prev = edge.back();
}
}
true
}
/// Returns whether the front vertex of the wire is the same as the back one or not.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// ]);
/// assert!(!wire.is_cyclic());
/// wire.push_back(Edge::new(&v[3], &v[0], ()));
/// assert!(wire.is_cyclic());
/// ```
/// ```
/// use truck_topology::*;
/// // The empty wire is cyclic.
/// assert!(Wire::<(), ()>::new().is_cyclic());
/// ```
#[inline(always)]
pub fn is_cyclic(&self) -> bool { self.front_vertex() == self.back_vertex() }
/// Returns whether the wire is closed or not.
/// Here, "closed" means "continuous" and "cyclic".
#[inline(always)]
pub fn is_closed(&self) -> bool { self.is_continuous() && self.is_cyclic() }
/// Returns whether simple or not.
/// Here, "simple" means all the vertices in the wire are shared from only two edges at most.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let edge0 = Edge::new(&v[0], &v[1], ());
/// let edge1 = Edge::new(&v[1], &v[2], ());
/// let edge2 = Edge::new(&v[2], &v[3], ());
/// let edge3 = Edge::new(&v[3], &v[1], ());
/// let edge4 = Edge::new(&v[3], &v[0], ());
///
/// let wire0 = Wire::from_iter(vec![&edge0, &edge1, &edge2, &edge3]);
/// let wire1 = Wire::from(vec![edge0, edge1, edge2, edge4]);
///
/// assert!(!wire0.is_simple());
/// assert!(wire1.is_simple());
/// ```
/// ```
/// use truck_topology::*;
/// // The empty wire is simple.
/// assert!(Wire::<(), ()>::new().is_simple());
/// ```
pub fn is_simple(&self) -> bool {
let mut set = HashSet::default();
self.vertex_iter()
.all(move |vertex| set.insert(vertex.id()))
}
/// Determines whether all the wires in `wires` has no same vertices.
/// # Examples
/// ```
/// use truck_topology::*;
///
/// let v = Vertex::news(&[(), (), (), (), ()]);
/// let edge0 = Edge::new(&v[0], &v[1], ());
/// let edge1 = Edge::new(&v[1], &v[2], ());
/// let edge2 = Edge::new(&v[2], &v[3], ());
/// let edge3 = Edge::new(&v[3], &v[4], ());
///
/// let wire0 = Wire::from(vec![edge0, edge1]);
/// let wire1 = Wire::from(vec![edge2]);
/// let wire2 = Wire::from(vec![edge3]);
///
/// assert!(Wire::disjoint_wires(&[wire0.clone(), wire2]));
/// assert!(!Wire::disjoint_wires(&[wire0, wire1]));
/// ```
pub fn disjoint_wires(wires: &[Wire<P, C>]) -> bool {
let mut set = HashSet::default();
wires.iter().all(move |wire| {
let mut vec = Vec::new();
let res = wire.vertex_iter().all(|v| {
vec.push(v.id());
!set.contains(&v.id())
});
set.extend(vec);
res
})
}
/// Swap one edge into two edges.
///
/// # Arguments
/// - `idx`: Index of edge in wire
/// - `edges`: Inserted edges
///
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), ()]);
/// let edge0 = Edge::new(&v[0], &v[1], 0);
/// let edge1 = Edge::new(&v[1], &v[3], 1);
/// let edge2 = Edge::new(&v[3], &v[4], 2);
/// let edge3 = Edge::new(&v[1], &v[2], 3);
/// let edge4 = Edge::new(&v[2], &v[3], 4);
/// let mut wire0 = Wire::from(vec![
/// edge0.clone(), edge1, edge2.clone()
/// ]);
/// let wire1 = Wire::from(vec![
/// edge0, edge3.clone(), edge4.clone(), edge2
/// ]);
/// assert_ne!(wire0, wire1);
/// wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4]));
/// assert_eq!(wire0, wire1);
/// ```
///
/// # Panics
/// Panic occars if `idx >= self.len()`.
///
/// # Failure
/// Returns `false` and `self` will not be changed if the end vertices of `self[idx]` and the ones of `wire` is not the same.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), ()]);
/// let edge0 = Edge::new(&v[0], &v[1], 0);
/// let edge1 = Edge::new(&v[1], &v[3], 1);
/// let edge2 = Edge::new(&v[3], &v[4], 2);
/// let edge3 = Edge::new(&v[1], &v[2], 3);
/// let edge4 = Edge::new(&v[2], &v[1], 4);
/// let mut wire0 = Wire::from(vec![
/// edge0.clone(), edge1, edge2.clone()
/// ]);
/// let backup = wire0.clone();
/// // The end vertices of wire[1] == edge1 is (v[1], v[3]).
/// // The end points of new wire [edge3, edge4] is (v[1], v[1]).
/// // Since the back vertices are different, returns false and do nothing.
/// assert!(!wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4])));
/// assert_eq!(wire0, backup);
/// ```
pub fn swap_edge_into_wire(&mut self, idx: usize, wire: Wire<P, C>) -> bool {
if wire.is_empty() || self[idx].ends() != wire.ends_vertices().unwrap() {
return false;
}
let mut new_wire: Vec<_> = self.drain(0..idx).collect();
new_wire.extend(wire);
self.pop_front();
new_wire.extend(self.drain(..));
*self = new_wire.into();
true
}
/// Concat edges
pub(super) fn swap_subwire_into_edges(&mut self, mut idx: usize, edge: Edge<P, C>) {
if idx + 1 == self.len() {
self.rotate_left(1);
idx -= 1;
}
let mut new_wire: Vec<_> = self.drain(0..idx).collect();
new_wire.push(edge);
self.pop_front();
self.pop_front();
new_wire.extend(self.drain(..));
*self = new_wire.into();
}
pub(super) fn sub_try_mapped<'a, Q, D, KF, KV>(
&'a self,
edge_map: &mut EdgeEntryMapForTryMapping<'a, P, C, Q, D, KF, KV>,
) -> Option<Wire<Q, D>>
where
KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
KV: FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>>,
{
self.edge_iter()
.map(|edge| Some(edge_map.entry_or_insert(edge).as_ref()?.absolute_clone()))
.collect()
}
/// Returns a new wire whose curves are mapped by `curve_mapping` and
/// whose points are mapped by `point_mapping`.
/// # Remarks
/// Accessing geometry elements directly in the closure will result in a deadlock.
/// So, this method does not appear to the document.
#[doc(hidden)]
pub fn try_mapped<Q, D>(
&self,
mut point_mapping: impl FnMut(&P) -> Option<Q>,
mut curve_mapping: impl FnMut(&C) -> Option<D>,
) -> Option<Wire<Q, D>> {
let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.try_mapped(&mut point_mapping));
let mut edge_map = EntryMap::new(
Edge::id,
edge_entry_map_try_closure(&mut vertex_map, &mut curve_mapping),
);
self.sub_try_mapped(&mut edge_map)
}
pub(super) fn sub_mapped<'a, Q, D, KF, KV>(
&'a self,
edge_map: &mut EdgeEntryMapForMapping<'a, P, C, Q, D, KF, KV>,
) -> Wire<Q, D>
where
KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
KV: FnMut(&'a Edge<P, C>) -> Edge<Q, D>,
{
self.edge_iter()
.map(|edge| {
let new_edge = edge_map.entry_or_insert(edge);
match edge.orientation() {
true => new_edge.clone(),
false => new_edge.inverse(),
}
})
.collect()
}
/// Returns a new wire whose curves are mapped by `curve_mapping` and
/// whose points are mapped by `point_mapping`.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[0, 1, 2, 3, 4]);
/// let wire0: Wire<usize, usize> = vec![
/// Edge::new(&v[0], &v[1], 100),
/// Edge::new(&v[2], &v[1], 110).inverse(),
/// Edge::new(&v[3], &v[4], 120),
/// Edge::new(&v[4], &v[0], 130),
/// ].into();
/// let wire1 = wire0.mapped(
/// &move |i: &usize| *i as f64 + 0.5,
/// &move |j: &usize| *j as f64 + 1000.5,
/// );
///
/// // Check the points
/// for (v0, v1) in wire0.vertex_iter().zip(wire1.vertex_iter()) {
/// let i = v0.get_point();
/// let j = v1.get_point();
/// assert_eq!(i as f64 + 0.5, j);
/// }
///
/// // Check the curves and orientation
/// for (edge0, edge1) in wire0.edge_iter().zip(wire1.edge_iter()) {
/// let i = edge0.get_curve();
/// let j = edge1.get_curve();
/// assert_eq!(i as f64 + 1000.5, j);
/// assert_eq!(edge0.orientation(), edge1.orientation());
/// }
///
/// // Check the connection
/// assert_eq!(wire1[0].back(), wire1[1].front());
/// assert_ne!(wire1[1].back(), wire1[2].front());
/// assert_eq!(wire1[2].back(), wire1[3].front());
/// assert_eq!(wire1[3].back(), wire1[0].front());
/// ```
/// # Remarks
/// Accessing geometry elements directly in the closure will result in a deadlock.
/// So, this method does not appear to the document.
#[doc(hidden)]
pub fn mapped<Q, D>(
&self,
mut point_mapping: impl FnMut(&P) -> Q,
mut curve_mapping: impl FnMut(&C) -> D,
) -> Wire<Q, D> {
let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.mapped(&mut point_mapping));
let mut edge_map = EntryMap::new(
Edge::id,
edge_entry_map_closure(&mut vertex_map, &mut curve_mapping),
);
self.sub_mapped(&mut edge_map)
}
/// Returns the consistence of the geometry of end vertices
/// and the geometry of edge.
#[inline(always)]
pub fn is_geometric_consistent(&self) -> bool
where
P: Tolerance,
C: BoundedCurve<Point = P>, {
self.iter().all(|edge| edge.is_geometric_consistent())
}
/// Creates display struct for debugging the wire.
/// # Examples
/// ```
/// use truck_topology::*;
/// use WireDisplayFormat as WDF;
/// let v = Vertex::news(&[0, 1, 2, 3, 4]);
/// let wire: Wire<usize, usize> = vec![
/// Edge::new(&v[0], &v[1], 100),
/// Edge::new(&v[2], &v[1], 110).inverse(),
/// Edge::new(&v[3], &v[4], 120),
/// ].into();
///
/// let vertex_format = VertexDisplayFormat::AsPoint;
/// let edge_format = EdgeDisplayFormat::VerticesTuple { vertex_format };
///
/// assert_eq!(
/// &format!("{:?}", wire.display(WDF::EdgesListTuple {edge_format})),
/// "Wire([(0, 1), (1, 2), (3, 4)])",
/// );
/// assert_eq!(
/// &format!("{:?}", wire.display(WDF::EdgesList {edge_format})),
/// "[(0, 1), (1, 2), (3, 4)]",
/// );
/// assert_eq!(
/// &format!("{:?}", wire.display(WDF::VerticesList {vertex_format})),
/// "[0, 1, 2, 3, 4]",
/// );
/// ```
#[inline(always)]
pub fn display(&self, format: WireDisplayFormat) -> DebugDisplay<'_, Self, WireDisplayFormat> {
DebugDisplay {
entity: self,
format,
}
}
}
type EdgeEntryMapForTryMapping<'a, P, C, Q, D, KF, KV> =
EntryMap<EdgeID<C>, Option<Edge<Q, D>>, KF, KV, &'a Edge<P, C>>;
type EdgeEntryMapForMapping<'a, P, C, Q, D, KF, KV> =
EntryMap<EdgeID<C>, Edge<Q, D>, KF, KV, &'a Edge<P, C>>;
pub(super) fn edge_entry_map_try_closure<'a, P, C, Q, D, KF, VF>(
vertex_map: &'a mut EntryMap<VertexID<P>, Option<Vertex<Q>>, KF, VF, &'a Vertex<P>>,
curve_mapping: &'a mut impl FnMut(&C) -> Option<D>,
) -> impl FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>> + 'a
where
KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
VF: FnMut(&'a Vertex<P>) -> Option<Vertex<Q>>,
{
move |edge| {
let vf = edge.absolute_front();
let vertex0 = vertex_map.entry_or_insert(vf).clone()?;
let vb = edge.absolute_back();
let vertex1 = vertex_map.entry_or_insert(vb).clone()?;
let curve = curve_mapping(&*edge.curve.lock().unwrap())?;
Some(Edge::debug_new(&vertex0, &vertex1, curve))
}
}
pub(super) fn edge_entry_map_closure<'a, P, C, Q, D, KF, VF>(
vertex_map: &'a mut EntryMap<VertexID<P>, Vertex<Q>, KF, VF, &'a Vertex<P>>,
curve_mapping: &'a mut impl FnMut(&C) -> D,
) -> impl FnMut(&'a Edge<P, C>) -> Edge<Q, D> + 'a
where
KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
VF: FnMut(&'a Vertex<P>) -> Vertex<Q>,
{
move |edge| {
let vf = edge.absolute_front();
let vertex0 = vertex_map.entry_or_insert(vf).clone();
let vb = edge.absolute_back();
let vertex1 = vertex_map.entry_or_insert(vb).clone();
let curve = curve_mapping(&*edge.curve.lock().unwrap());
Edge::debug_new(&vertex0, &vertex1, curve)
}
}
impl<T, P, C> From<T> for Wire<P, C>
where T: Into<VecDeque<Edge<P, C>>>
{
#[inline(always)]
fn from(edge_list: T) -> Wire<P, C> {
Wire {
edge_list: edge_list.into(),
}
}
}
impl<P, C> FromIterator<Edge<P, C>> for Wire<P, C> {
#[inline(always)]
fn from_iter<I: IntoIterator<Item = Edge<P, C>>>(iter: I) -> Wire<P, C> {
Wire::from(VecDeque::from_iter(iter))
}
}
impl<'a, P, C> FromIterator<&'a Edge<P, C>> for Wire<P, C> {
#[inline(always)]
fn from_iter<I: IntoIterator<Item = &'a Edge<P, C>>>(iter: I) -> Wire<P, C> {
Wire::from(VecDeque::from_iter(iter.into_iter().map(Edge::clone)))
}
}
impl<P, C> IntoIterator for Wire<P, C> {
type Item = Edge<P, C>;
type IntoIter = EdgeIntoIter<P, C>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter { self.edge_list.into_iter() }
}
impl<'a, P, C> IntoIterator for &'a Wire<P, C> {
type Item = &'a Edge<P, C>;
type IntoIter = EdgeIter<'a, P, C>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter { self.edge_list.iter() }
}
/// The reference iterator over all edges in a wire.
pub type EdgeIter<'a, P, C> = vec_deque::Iter<'a, Edge<P, C>>;
/// The mutable reference iterator over all edges in a wire.
pub type EdgeIterMut<'a, P, C> = vec_deque::IterMut<'a, Edge<P, C>>;
/// The into iterator over all edges in a wire.
pub type EdgeIntoIter<P, C> = vec_deque::IntoIter<Edge<P, C>>;
/// The reference parallel iterator over all edges in a wire.
pub type EdgeParallelIter<'a, P, C> = <VecDeque<Edge<P, C>> as IntoParallelRefIterator<'a>>::Iter;
/// The mutable reference parallel iterator over all edges in a wire.
pub type EdgeParallelIterMut<'a, P, C> =
<VecDeque<Edge<P, C>> as IntoParallelRefMutIterator<'a>>::Iter;
/// the parallel iterator over all edges in a wire.
pub type EdgeParallelIntoIter<P, C> = <VecDeque<Edge<P, C>> as IntoParallelIterator>::Iter;
/// The iterator over all the vertices included in a wire.
/// # Details
/// Fundamentally, the iterator runs over all the vertices in a wire.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 6]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// Edge::new(&v[4], &v[5], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next().as_ref(), Some(&v[5]));
/// assert_eq!(viter.next(), None);
/// assert_eq!(viter.next(), None); // VertexIter is a FusedIterator.
/// ```
/// If a pair of adjacent edges share one vertex, the iterator run only one time at the shared vertex.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 6]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[5], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next().as_ref(), Some(&v[5]));
/// assert_eq!(viter.next(), None);
/// ```
/// If the wire is cyclic, the iterator does not arrive at the last vertex.
/// ```
/// # use truck_topology::*;
/// let v = Vertex::news(&[(); 5]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[0], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next(), None);
/// ```
#[derive(Clone, Debug)]
pub struct VertexIter<'a, P, C> {
edge_iter: Peekable<EdgeIter<'a, P, C>>,
unconti_next: Option<Vertex<P>>,
cyclic: bool,
}
impl<'a, P, C> Iterator for VertexIter<'a, P, C> {
type Item = Vertex<P>;
fn next(&mut self) -> Option<Vertex<P>> {
if self.unconti_next.is_some() {
let res = self.unconti_next.clone();
self.unconti_next = None;
res
} else if let Some(edge) = self.edge_iter.next() {
if let Some(next) = self.edge_iter.peek() {
if edge.back() != next.front() {
self.unconti_next = Some(edge.back().clone());
}
} else if !self.cyclic {
self.unconti_next = Some(edge.back().clone());
}
Some(edge.front().clone())
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let min_size = self.edge_iter.len();
let max_size = self.edge_iter.len() * 2;
(min_size, Some(max_size))
}
fn last(self) -> Option<Vertex<P>> {
let closed = self.cyclic;
self.edge_iter.last().map(|edge| {
if closed {
edge.front().clone()
} else {
edge.back().clone()
}
})
}
}
impl<'a, P, C> std::iter::FusedIterator for VertexIter<'a, P, C> {}
impl<P, C> Extend<Edge<P, C>> for Wire<P, C> {
fn extend<T: IntoIterator<Item = Edge<P, C>>>(&mut self, iter: T) {
for edge in iter {
self.push_back(edge);
}
}
}
impl<P, C> std::ops::Deref for Wire<P, C> {
type Target = VecDeque<Edge<P, C>>;
#[inline(always)]
fn deref(&self) -> &Self::Target { &self.edge_list }
}
impl<P, C> std::ops::DerefMut for Wire<P, C> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.edge_list }
}
impl<P, C> Clone for Wire<P, C> {
#[inline(always)]
fn clone(&self) -> Self {
Self {
edge_list: self.edge_list.clone(),
}
}
}
impl<P, C> PartialEq for Wire<P, C> {
#[inline(always)]
fn eq(&self, other: &Self) -> bool { self.edge_list == other.edge_list }
}
impl<P, C> Eq for Wire<P, C> {}
impl<P, C> Default for Wire<P, C> {
#[inline(always)]
fn default() -> Self {
Self {
edge_list: Default::default(),
}
}
}
impl<'a, P: Debug, C: Debug> Debug for DebugDisplay<'a, Wire<P, C>, WireDisplayFormat> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.format {
WireDisplayFormat::EdgesListTuple { edge_format } => f
.debug_tuple("Wire")
.field(&Self {
entity: self.entity,
format: WireDisplayFormat::EdgesList { edge_format },
})
.finish(),
WireDisplayFormat::EdgesList { edge_format } => f
.debug_list()
.entries(
self.entity
.edge_iter()
.map(|edge| edge.display(edge_format)),
)
.finish(),
WireDisplayFormat::VerticesList { vertex_format } => {
let vertices: Vec<_> = self.entity.vertex_iter().collect();
f.debug_list()
.entries(vertices.iter().map(|vertex| vertex.display(vertex_format)))
.finish()
}
}
}
More examples
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
pub fn boundary_iters(&self) -> Vec<BoundaryIter<'_, P, C>> {
self.boundaries
.iter()
.map(|wire| BoundaryIter {
edge_iter: wire.edge_iter(),
orientation: self.orientation,
})
.collect()
}
#[inline(always)]
fn renew_pointer(&mut self)
where S: Clone {
let surface = self.get_surface();
self.surface = Arc::new(Mutex::new(surface));
}
/// Returns an iterator over the edges.
#[inline(always)]
pub fn edge_iter(&self) -> impl Iterator<Item = Edge<P, C>> + '_ {
self.boundary_iters().into_iter().flatten()
}
/// Returns an iterator over the vertices.
#[inline(always)]
pub fn vertex_iter(&self) -> impl Iterator<Item = Vertex<P>> + '_ {
self.edge_iter().map(|e| e.front().clone())
}
/// Adds a boundary to the face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[5], ()),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face0 = Face::new(vec![wire0.clone()], ());
/// face0.try_add_boundary(wire1.clone()).unwrap();
/// let face1 = Face::new(vec![wire0, wire1], ());
/// assert_eq!(face0.boundaries(), face1.boundaries());
/// ```
/// # Remarks
/// 1. If the face is inverted, then the added wire is inverted as absolute boundary.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[5], &v[4], ()).inverse(),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face = Face::new(vec![wire0], ());
/// face.invert();
/// face.try_add_boundary(wire1.clone()).unwrap();
///
/// // The boundary is added in compatible with the face orientation.
/// assert_eq!(face.boundaries()[1], wire1);
///
/// // The absolute boundary is inverted!
/// let iter0 = face.absolute_boundaries()[1].edge_iter();
/// let iter1 = wire1.edge_iter().rev();
/// for (edge0, edge1) in iter0.zip(iter1) {
/// assert_eq!(edge0.id(), edge1.id());
/// assert_eq!(edge0.orientation(), !edge1.orientation());
/// }
/// ```
/// 2. This method renew the face id.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[5], &v[4], ()).inverse(),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face0 = Face::new(vec![wire0], ());
/// let face1 = face0.clone();
/// assert_eq!(face0.id(), face1.id());
/// face0.try_add_boundary(wire1).unwrap();
/// assert_ne!(face0.id(), face1.id());
/// ```
#[inline(always)]
pub fn try_add_boundary(&mut self, mut wire: Wire<P, C>) -> Result<()>
where S: Clone {
if wire.is_empty() {
return Err(Error::EmptyWire);
} else if !wire.is_closed() {
return Err(Error::NotClosedWire);
} else if !wire.is_simple() {
return Err(Error::NotSimpleWire);
}
if !self.orientation {
wire.invert();
}
self.boundaries.push(wire);
self.renew_pointer();
if !Wire::disjoint_wires(&self.boundaries) {
self.boundaries.pop();
return Err(Error::NotDisjointWires);
}
Ok(())
}
/// Adds a boundary to the face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[5], ()),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face0 = Face::new(vec![wire0.clone()], ());
/// face0.add_boundary(wire1.clone());
/// let face1 = Face::new(vec![wire0, wire1], ());
/// assert_eq!(face0.boundaries(), face1.boundaries());
/// ```
/// # Remarks
/// 1. If the face is inverted, then the added wire is inverted as absolute boundary.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[5], &v[4], ()).inverse(),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face = Face::new(vec![wire0], ());
/// face.invert();
/// face.add_boundary(wire1.clone());
///
/// // The boundary is added in compatible with the face orientation.
/// assert_eq!(face.boundaries()[1], wire1);
///
/// // The absolute boundary is inverted!
/// let iter0 = face.absolute_boundaries()[1].edge_iter();
/// let iter1 = wire1.edge_iter().rev();
/// for (edge0, edge1) in iter0.zip(iter1) {
/// assert_eq!(edge0.id(), edge1.id());
/// assert_eq!(edge0.orientation(), !edge1.orientation());
/// }
/// ```
/// 2. This method renew the face id.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[5], &v[4], ()).inverse(),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face0 = Face::new(vec![wire0], ());
/// let face1 = face0.clone();
/// assert_eq!(face0.id(), face1.id());
/// face0.add_boundary(wire1);
/// assert_ne!(face0.id(), face1.id());
/// ```
#[inline(always)]
pub fn add_boundary(&mut self, wire: Wire<P, C>)
where S: Clone {
self.try_add_boundary(wire).remove_try()
}
/// Returns a new face whose surface is mapped by `surface_mapping`,
/// curves are mapped by `curve_mapping` and points are mapped by `point_mapping`.
/// # Remarks
/// Accessing geometry elements directly in the closure will result in a deadlock.
/// So, this method does not appear to the document.
#[doc(hidden)]
pub fn try_mapped<Q, D, T>(
&self,
mut point_mapping: impl FnMut(&P) -> Option<Q>,
mut curve_mapping: impl FnMut(&C) -> Option<D>,
mut surface_mapping: impl FnMut(&S) -> Option<T>,
) -> Option<Face<Q, D, T>> {
let wires = self
.absolute_boundaries()
.iter()
.map(|wire| wire.try_mapped(&mut point_mapping, &mut curve_mapping))
.collect::<Option<Vec<_>>>()?;
let surface = surface_mapping(&*self.surface.lock().unwrap())?;
let mut face = Face::debug_new(wires, surface);
if !self.orientation() {
face.invert();
}
Some(face)
}
/// Returns a new face whose surface is mapped by `surface_mapping`,
/// curves are mapped by `curve_mapping` and points are mapped by `point_mapping`.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[0, 1, 2, 3, 4, 5, 6]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], 100),
/// Edge::new(&v[1], &v[2], 200),
/// Edge::new(&v[2], &v[3], 300),
/// Edge::new(&v[3], &v[0], 400),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[4], &v[5], 500),
/// Edge::new(&v[6], &v[5], 600).inverse(),
/// Edge::new(&v[6], &v[4], 700),
/// ]);
/// let face0 = Face::new(vec![wire0, wire1], 10000);
/// let face1 = face0.mapped(
/// &move |i: &usize| *i + 10,
/// &move |j: &usize| *j + 1000,
/// &move |k: &usize| *k + 100000,
/// );
/// # for wire in face1.boundaries() {
/// # assert!(wire.is_closed());
/// # assert!(wire.is_simple());
/// # }
///
/// assert_eq!(
/// face0.get_surface() + 100000,
/// face1.get_surface(),
/// );
/// let biters0 = face0.boundary_iters();
/// let biters1 = face1.boundary_iters();
/// for (biter0, biter1) in biters0.into_iter().zip(biters1) {
/// for (edge0, edge1) in biter0.zip(biter1) {
/// assert_eq!(
/// edge0.front().get_point() + 10,
/// edge1.front().get_point(),
/// );
/// assert_eq!(
/// edge0.back().get_point() + 10,
/// edge1.back().get_point(),
/// );
/// assert_eq!(edge0.orientation(), edge1.orientation());
/// assert_eq!(
/// edge0.get_curve() + 1000,
/// edge1.get_curve(),
/// );
/// }
/// }
/// ```
/// # Remarks
/// Accessing geometry elements directly in the closure will result in a deadlock.
/// So, this method does not appear to the document.
#[doc(hidden)]
pub fn mapped<Q, D, T>(
&self,
mut point_mapping: impl FnMut(&P) -> Q,
mut curve_mapping: impl FnMut(&C) -> D,
mut surface_mapping: impl FnMut(&S) -> T,
) -> Face<Q, D, T> {
let wires: Vec<_> = self
.absolute_boundaries()
.iter()
.map(|wire| wire.mapped(&mut point_mapping, &mut curve_mapping))
.collect();
let surface = surface_mapping(&*self.surface.lock().unwrap());
let mut face = Face::debug_new(wires, surface);
if !self.orientation() {
face.invert();
}
face
}
/// Returns the orientation of face.
///
/// The result of this method is the same with `self.boundaries() == self.absolute_boundaries().clone()`.
/// Moreover, if this method returns false, `self.boundaries() == self.absolute_boundaries().inverse()`.
#[inline(always)]
pub fn orientation(&self) -> bool { self.orientation }
/// Returns the clone of surface of face.
#[inline(always)]
pub fn get_surface(&self) -> S
where S: Clone {
self.surface.lock().unwrap().clone()
}
/// Sets the surface of face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let face0 = Face::new(vec![wire], 0);
/// let face1 = face0.clone();
///
/// // Two faces have the same content.
/// assert_eq!(face0.get_surface(), 0);
/// assert_eq!(face1.get_surface(), 0);
///
/// // Set surface
/// face0.set_surface(1);
///
/// // The contents of two vertices are synchronized.
/// assert_eq!(face0.get_surface(), 1);
/// assert_eq!(face1.get_surface(), 1);
/// ```
#[inline(always)]
pub fn set_surface(&self, surface: S) { *self.surface.lock().unwrap() = surface; }
/// Inverts the direction of the face.
/// # Examples
/// ```
/// use truck_topology::*;
/// use truck_topology::errors::Error;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let org_face = face.clone();
/// let org_bdry = face.boundaries();
/// face.invert();
///
/// // Two faces are the same face.
/// face.is_same(&org_face);
///
/// // The boundaries is inverted.
/// let inversed_edge_iter = org_bdry[0].inverse().edge_into_iter();
/// let face_edge_iter = &mut face.boundary_iters()[0];
/// for (edge0, edge1) in inversed_edge_iter.zip(face_edge_iter) {
/// assert_eq!(edge0, edge1);
/// }
/// ```
#[inline(always)]
pub fn invert(&mut self) -> &mut Self {
self.orientation = !self.orientation;
self
}
/// Returns whether two faces are the same. Returns `true` even if the orientaions are different.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 3]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let face0 = Face::new(vec![wire], ());
/// let face1 = face0.inverse();
/// assert_ne!(face0, face1);
/// assert!(face0.is_same(&face1));
/// ```
#[inline(always)]
pub fn is_same(&self, other: &Self) -> bool {
std::ptr::eq(Arc::as_ptr(&self.surface), Arc::as_ptr(&other.surface))
}
/// Returns the id that does not depend on the direction of the face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 3]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let face0 = Face::new(vec![wire.clone()], ());
/// let face1 = face0.inverse();
/// let face2 = Face::new(vec![wire], ());
/// assert_ne!(face0, face1);
/// assert_ne!(face0, face2);
/// assert_eq!(face0.id(), face1.id());
/// assert_ne!(face0.id(), face2.id());
/// ```
#[inline(always)]
pub fn id(&self) -> FaceID<S> { ID::new(Arc::as_ptr(&self.surface)) }
/// Returns how many same faces.
///
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 3]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
///
/// // Create one face
/// let face0 = Face::new(vec![wire.clone()], ());
/// assert_eq!(face0.count(), 1);
/// // Create another face, independent from face0
/// let face1 = Face::new(vec![wire.clone()], ());
/// assert_eq!(face0.count(), 1);
/// // Clone face0, the result will be 2.
/// let face2 = face0.clone();
/// assert_eq!(face0.count(), 2);
/// assert_eq!(face2.count(), 2);
/// // drop face2, the result will be 1.
/// drop(face2);
/// assert_eq!(face0.count(), 1);
/// ```
#[inline(always)]
pub fn count(&self) -> usize { Arc::strong_count(&self.surface) }
/// Returns the inverse face.
/// # Examples
/// ```
/// use truck_topology::*;
/// use truck_topology::errors::Error;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let inverted = face.inverse();
///
/// // Two faces are the same face.
/// assert!(face.is_same(&inverted));
///
/// // Two faces has the same id.
/// assert_eq!(face.id(), inverted.id());
///
/// // The boundaries is inverted.
/// let mut inversed_edge_iter = face.boundaries()[0].inverse().edge_into_iter();
/// let face_edge_iter = &mut inverted.boundary_iters()[0];
/// for (edge0, edge1) in inversed_edge_iter.zip(face_edge_iter) {
/// assert_eq!(edge0, edge1);
/// }
/// ```
#[inline(always)]
pub fn inverse(&self) -> Face<P, C, S> {
let mut face = self.clone();
face.invert();
face
}
/// Returns whether two faces `self` and `other` have a shared edge.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let shared_edge = Edge::new(&v[0], &v[1], ());
/// let another_edge = Edge::new(&v[0], &v[1], ());
/// let inversed_edge = shared_edge.inverse();
/// let wire = vec![
/// Wire::from_iter(vec![&Edge::new(&v[2], &v[0], ()), &shared_edge, &Edge::new(&v[1], &v[2], ())]),
/// Wire::from_iter(vec![&Edge::new(&v[2], &v[0], ()), &another_edge, &Edge::new(&v[1], &v[2], ())]),
/// Wire::from_iter(vec![&Edge::new(&v[3], &v[0], ()), &shared_edge, &Edge::new(&v[1], &v[3], ())]),
/// Wire::from_iter(vec![&Edge::new(&v[3], &v[1], ()), &inversed_edge, &Edge::new(&v[0], &v[3], ())]),
/// ];
/// let face: Vec<_> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
/// assert!(face[0].border_on(&face[2]));
/// assert!(!face[1].border_on(&face[2]));
/// assert!(face[0].border_on(&face[3]));
/// ```
pub fn border_on(&self, other: &Face<P, C, S>) -> bool {
let mut hashmap = HashMap::default();
let edge_iter = self.boundary_iters().into_iter().flatten();
edge_iter.for_each(|edge| {
hashmap.insert(edge.id(), edge);
});
let mut edge_iter = other.boundary_iters().into_iter().flatten();
edge_iter.any(|edge| hashmap.insert(edge.id(), edge).is_some())
}
/// Cuts a face with only one boundary by an edge.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[3], ()),
/// Edge::new(&v[3], &v[0], ()),
/// ]);
/// let face = Face::new(vec![wire], ());
/// let (face0, face1) = face.cut_by_edge(Edge::new(&v[1], &v[3], ())).unwrap();
///
/// // The front vertex of face0's boundary becomes the back of cutting edge.
/// let v0: Vec<Vertex<()>> = face0.boundaries()[0].vertex_iter().collect();
/// assert_eq!(v0, vec![v[3].clone(), v[0].clone(), v[1].clone()]);
///
/// let v1: Vec<Vertex<()>> = face1.boundaries()[0].vertex_iter().collect();
/// assert_eq!(v1, vec![v[1].clone(), v[2].clone(), v[3].clone()]);
/// ```
/// # Failures
/// Returns `None` if:
/// - `self` has several boundaries, or
/// - `self` does not include vertices of the end vertices of `edge`.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 6]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[5], ()),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let face = Face::new(vec![wire0, wire1], ());
/// assert!(face.cut_by_edge(Edge::new(&v[1], &v[2], ())).is_none());
/// ```
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[3], ()),
/// Edge::new(&v[3], &v[0], ()),
/// ]);
/// let face = Face::new(vec![wire], ());
/// assert!(face.cut_by_edge(Edge::new(&v[1], &v[4], ())).is_none());
pub fn cut_by_edge(&self, edge: Edge<P, C>) -> Option<(Self, Self)>
where S: Clone {
if self.boundaries.len() != 1 {
return None;
}
let mut face0 = Face {
boundaries: self.boundaries.clone(),
orientation: self.orientation,
surface: Arc::new(Mutex::new(self.get_surface())),
};
let wire = &mut face0.boundaries[0];
let i = wire
.edge_iter()
.enumerate()
.find(|(_, e)| e.front() == edge.back())
.map(|(i, _)| i)?;
let j = wire
.edge_iter()
.enumerate()
.find(|(_, e)| e.back() == edge.front())
.map(|(i, _)| i)?;
wire.rotate_left(i);
let j = (j + wire.len() - i) % wire.len();
let mut new_wire = wire.split_off(j + 1);
wire.push_back(edge.clone());
new_wire.push_back(edge.inverse());
debug_assert!(Face::try_new(self.boundaries.clone(), ()).is_ok());
debug_assert!(Face::try_new(vec![new_wire.clone()], ()).is_ok());
let face1 = Face {
boundaries: vec![new_wire],
orientation: self.orientation,
surface: Arc::new(Mutex::new(self.get_surface())),
};
Some((face0, face1))
}
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
pub fn remove_vertex_by_concat_edges(&mut self, vertex_id: VertexID<P>) -> Option<Edge<P, C>>
where
P: Debug,
C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
let mut vec: Vec<(&mut Wire<P, C>, usize)> = self
.face_iter_mut()
.flat_map(|face| &mut face.boundaries)
.filter_map(|wire| {
let idx = wire
.edge_iter()
.enumerate()
.find(|(_, e)| e.back().id() == vertex_id)?
.0;
Some((wire, idx))
})
.collect();
if vec.len() > 2 || vec.is_empty() {
None
} else if vec.len() == 1 {
let (wire, idx) = vec.pop().unwrap();
let edge = wire[idx].concat(&wire[(idx + 1) % wire.len()]).ok()?;
wire.swap_subwire_into_edges(idx, edge.clone());
Some(edge)
} else {
let (wire0, idx0) = vec.pop().unwrap();
let (wire1, idx1) = vec.pop().unwrap();
if !wire0[idx0].is_same(&wire1[(idx1 + 1) % wire1.len()])
|| !wire0[(idx0 + 1) % wire0.len()].is_same(&wire1[idx1])
{
return None;
}
let edge = wire0[idx0].concat(&wire0[(idx0 + 1) % wire0.len()]).ok()?;
wire1.swap_subwire_into_edges(idx1, edge.inverse());
wire0.swap_subwire_into_edges(idx0, edge.clone());
Some(edge)
}
}
sourcepub fn edge_iter_mut(&mut self) -> EdgeIterMut<'_, P, C>
pub fn edge_iter_mut(&mut self) -> EdgeIterMut<'_, P, C>
Returns a mutable iterator over the edges. Practically, an alias of iter_mut()
.
sourcepub fn edge_into_iter(self) -> EdgeIntoIter<P, C>
pub fn edge_into_iter(self) -> EdgeIntoIter<P, C>
Creates a consuming iterator. Practically, an alias of into_iter()
.
sourcepub fn edge_par_iter(&self) -> EdgeParallelIter<'_, P, C>where
P: Send,
C: Send,
pub fn edge_par_iter(&self) -> EdgeParallelIter<'_, P, C>where
P: Send,
C: Send,
Returns an parallel iterator over the edges. Practically, an alias of par_iter()
.
sourcepub fn edge_par_iter_mut(&mut self) -> EdgeParallelIterMut<'_, P, C>where
P: Send,
C: Send,
pub fn edge_par_iter_mut(&mut self) -> EdgeParallelIterMut<'_, P, C>where
P: Send,
C: Send,
Returns a mutable parallel iterator over the edges. Practically, an alias of par_iter_mut()
.
sourcepub fn edge_into_par_iter(self) -> EdgeParallelIntoIter<P, C>where
P: Send,
C: Send,
pub fn edge_into_par_iter(self) -> EdgeParallelIntoIter<P, C>where
P: Send,
C: Send,
Creates a consuming iterator. Practically, an alias of into_par_iter()
.
sourcepub fn vertex_iter(&self) -> VertexIter<'_, P, C> ⓘ
pub fn vertex_iter(&self) -> VertexIter<'_, P, C> ⓘ
Returns an iterator over the vertices.
Examples found in repository?
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
pub fn is_simple(&self) -> bool {
let mut set = HashSet::default();
self.vertex_iter()
.all(move |vertex| set.insert(vertex.id()))
}
/// Determines whether all the wires in `wires` has no same vertices.
/// # Examples
/// ```
/// use truck_topology::*;
///
/// let v = Vertex::news(&[(), (), (), (), ()]);
/// let edge0 = Edge::new(&v[0], &v[1], ());
/// let edge1 = Edge::new(&v[1], &v[2], ());
/// let edge2 = Edge::new(&v[2], &v[3], ());
/// let edge3 = Edge::new(&v[3], &v[4], ());
///
/// let wire0 = Wire::from(vec![edge0, edge1]);
/// let wire1 = Wire::from(vec![edge2]);
/// let wire2 = Wire::from(vec![edge3]);
///
/// assert!(Wire::disjoint_wires(&[wire0.clone(), wire2]));
/// assert!(!Wire::disjoint_wires(&[wire0, wire1]));
/// ```
pub fn disjoint_wires(wires: &[Wire<P, C>]) -> bool {
let mut set = HashSet::default();
wires.iter().all(move |wire| {
let mut vec = Vec::new();
let res = wire.vertex_iter().all(|v| {
vec.push(v.id());
!set.contains(&v.id())
});
set.extend(vec);
res
})
}
/// Swap one edge into two edges.
///
/// # Arguments
/// - `idx`: Index of edge in wire
/// - `edges`: Inserted edges
///
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), ()]);
/// let edge0 = Edge::new(&v[0], &v[1], 0);
/// let edge1 = Edge::new(&v[1], &v[3], 1);
/// let edge2 = Edge::new(&v[3], &v[4], 2);
/// let edge3 = Edge::new(&v[1], &v[2], 3);
/// let edge4 = Edge::new(&v[2], &v[3], 4);
/// let mut wire0 = Wire::from(vec![
/// edge0.clone(), edge1, edge2.clone()
/// ]);
/// let wire1 = Wire::from(vec![
/// edge0, edge3.clone(), edge4.clone(), edge2
/// ]);
/// assert_ne!(wire0, wire1);
/// wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4]));
/// assert_eq!(wire0, wire1);
/// ```
///
/// # Panics
/// Panic occars if `idx >= self.len()`.
///
/// # Failure
/// Returns `false` and `self` will not be changed if the end vertices of `self[idx]` and the ones of `wire` is not the same.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), ()]);
/// let edge0 = Edge::new(&v[0], &v[1], 0);
/// let edge1 = Edge::new(&v[1], &v[3], 1);
/// let edge2 = Edge::new(&v[3], &v[4], 2);
/// let edge3 = Edge::new(&v[1], &v[2], 3);
/// let edge4 = Edge::new(&v[2], &v[1], 4);
/// let mut wire0 = Wire::from(vec![
/// edge0.clone(), edge1, edge2.clone()
/// ]);
/// let backup = wire0.clone();
/// // The end vertices of wire[1] == edge1 is (v[1], v[3]).
/// // The end points of new wire [edge3, edge4] is (v[1], v[1]).
/// // Since the back vertices are different, returns false and do nothing.
/// assert!(!wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4])));
/// assert_eq!(wire0, backup);
/// ```
pub fn swap_edge_into_wire(&mut self, idx: usize, wire: Wire<P, C>) -> bool {
if wire.is_empty() || self[idx].ends() != wire.ends_vertices().unwrap() {
return false;
}
let mut new_wire: Vec<_> = self.drain(0..idx).collect();
new_wire.extend(wire);
self.pop_front();
new_wire.extend(self.drain(..));
*self = new_wire.into();
true
}
/// Concat edges
pub(super) fn swap_subwire_into_edges(&mut self, mut idx: usize, edge: Edge<P, C>) {
if idx + 1 == self.len() {
self.rotate_left(1);
idx -= 1;
}
let mut new_wire: Vec<_> = self.drain(0..idx).collect();
new_wire.push(edge);
self.pop_front();
self.pop_front();
new_wire.extend(self.drain(..));
*self = new_wire.into();
}
pub(super) fn sub_try_mapped<'a, Q, D, KF, KV>(
&'a self,
edge_map: &mut EdgeEntryMapForTryMapping<'a, P, C, Q, D, KF, KV>,
) -> Option<Wire<Q, D>>
where
KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
KV: FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>>,
{
self.edge_iter()
.map(|edge| Some(edge_map.entry_or_insert(edge).as_ref()?.absolute_clone()))
.collect()
}
/// Returns a new wire whose curves are mapped by `curve_mapping` and
/// whose points are mapped by `point_mapping`.
/// # Remarks
/// Accessing geometry elements directly in the closure will result in a deadlock.
/// So, this method does not appear to the document.
#[doc(hidden)]
pub fn try_mapped<Q, D>(
&self,
mut point_mapping: impl FnMut(&P) -> Option<Q>,
mut curve_mapping: impl FnMut(&C) -> Option<D>,
) -> Option<Wire<Q, D>> {
let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.try_mapped(&mut point_mapping));
let mut edge_map = EntryMap::new(
Edge::id,
edge_entry_map_try_closure(&mut vertex_map, &mut curve_mapping),
);
self.sub_try_mapped(&mut edge_map)
}
pub(super) fn sub_mapped<'a, Q, D, KF, KV>(
&'a self,
edge_map: &mut EdgeEntryMapForMapping<'a, P, C, Q, D, KF, KV>,
) -> Wire<Q, D>
where
KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
KV: FnMut(&'a Edge<P, C>) -> Edge<Q, D>,
{
self.edge_iter()
.map(|edge| {
let new_edge = edge_map.entry_or_insert(edge);
match edge.orientation() {
true => new_edge.clone(),
false => new_edge.inverse(),
}
})
.collect()
}
/// Returns a new wire whose curves are mapped by `curve_mapping` and
/// whose points are mapped by `point_mapping`.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[0, 1, 2, 3, 4]);
/// let wire0: Wire<usize, usize> = vec![
/// Edge::new(&v[0], &v[1], 100),
/// Edge::new(&v[2], &v[1], 110).inverse(),
/// Edge::new(&v[3], &v[4], 120),
/// Edge::new(&v[4], &v[0], 130),
/// ].into();
/// let wire1 = wire0.mapped(
/// &move |i: &usize| *i as f64 + 0.5,
/// &move |j: &usize| *j as f64 + 1000.5,
/// );
///
/// // Check the points
/// for (v0, v1) in wire0.vertex_iter().zip(wire1.vertex_iter()) {
/// let i = v0.get_point();
/// let j = v1.get_point();
/// assert_eq!(i as f64 + 0.5, j);
/// }
///
/// // Check the curves and orientation
/// for (edge0, edge1) in wire0.edge_iter().zip(wire1.edge_iter()) {
/// let i = edge0.get_curve();
/// let j = edge1.get_curve();
/// assert_eq!(i as f64 + 1000.5, j);
/// assert_eq!(edge0.orientation(), edge1.orientation());
/// }
///
/// // Check the connection
/// assert_eq!(wire1[0].back(), wire1[1].front());
/// assert_ne!(wire1[1].back(), wire1[2].front());
/// assert_eq!(wire1[2].back(), wire1[3].front());
/// assert_eq!(wire1[3].back(), wire1[0].front());
/// ```
/// # Remarks
/// Accessing geometry elements directly in the closure will result in a deadlock.
/// So, this method does not appear to the document.
#[doc(hidden)]
pub fn mapped<Q, D>(
&self,
mut point_mapping: impl FnMut(&P) -> Q,
mut curve_mapping: impl FnMut(&C) -> D,
) -> Wire<Q, D> {
let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.mapped(&mut point_mapping));
let mut edge_map = EntryMap::new(
Edge::id,
edge_entry_map_closure(&mut vertex_map, &mut curve_mapping),
);
self.sub_mapped(&mut edge_map)
}
/// Returns the consistence of the geometry of end vertices
/// and the geometry of edge.
#[inline(always)]
pub fn is_geometric_consistent(&self) -> bool
where
P: Tolerance,
C: BoundedCurve<Point = P>, {
self.iter().all(|edge| edge.is_geometric_consistent())
}
/// Creates display struct for debugging the wire.
/// # Examples
/// ```
/// use truck_topology::*;
/// use WireDisplayFormat as WDF;
/// let v = Vertex::news(&[0, 1, 2, 3, 4]);
/// let wire: Wire<usize, usize> = vec![
/// Edge::new(&v[0], &v[1], 100),
/// Edge::new(&v[2], &v[1], 110).inverse(),
/// Edge::new(&v[3], &v[4], 120),
/// ].into();
///
/// let vertex_format = VertexDisplayFormat::AsPoint;
/// let edge_format = EdgeDisplayFormat::VerticesTuple { vertex_format };
///
/// assert_eq!(
/// &format!("{:?}", wire.display(WDF::EdgesListTuple {edge_format})),
/// "Wire([(0, 1), (1, 2), (3, 4)])",
/// );
/// assert_eq!(
/// &format!("{:?}", wire.display(WDF::EdgesList {edge_format})),
/// "[(0, 1), (1, 2), (3, 4)]",
/// );
/// assert_eq!(
/// &format!("{:?}", wire.display(WDF::VerticesList {vertex_format})),
/// "[0, 1, 2, 3, 4]",
/// );
/// ```
#[inline(always)]
pub fn display(&self, format: WireDisplayFormat) -> DebugDisplay<'_, Self, WireDisplayFormat> {
DebugDisplay {
entity: self,
format,
}
}
}
type EdgeEntryMapForTryMapping<'a, P, C, Q, D, KF, KV> =
EntryMap<EdgeID<C>, Option<Edge<Q, D>>, KF, KV, &'a Edge<P, C>>;
type EdgeEntryMapForMapping<'a, P, C, Q, D, KF, KV> =
EntryMap<EdgeID<C>, Edge<Q, D>, KF, KV, &'a Edge<P, C>>;
pub(super) fn edge_entry_map_try_closure<'a, P, C, Q, D, KF, VF>(
vertex_map: &'a mut EntryMap<VertexID<P>, Option<Vertex<Q>>, KF, VF, &'a Vertex<P>>,
curve_mapping: &'a mut impl FnMut(&C) -> Option<D>,
) -> impl FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>> + 'a
where
KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
VF: FnMut(&'a Vertex<P>) -> Option<Vertex<Q>>,
{
move |edge| {
let vf = edge.absolute_front();
let vertex0 = vertex_map.entry_or_insert(vf).clone()?;
let vb = edge.absolute_back();
let vertex1 = vertex_map.entry_or_insert(vb).clone()?;
let curve = curve_mapping(&*edge.curve.lock().unwrap())?;
Some(Edge::debug_new(&vertex0, &vertex1, curve))
}
}
pub(super) fn edge_entry_map_closure<'a, P, C, Q, D, KF, VF>(
vertex_map: &'a mut EntryMap<VertexID<P>, Vertex<Q>, KF, VF, &'a Vertex<P>>,
curve_mapping: &'a mut impl FnMut(&C) -> D,
) -> impl FnMut(&'a Edge<P, C>) -> Edge<Q, D> + 'a
where
KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
VF: FnMut(&'a Vertex<P>) -> Vertex<Q>,
{
move |edge| {
let vf = edge.absolute_front();
let vertex0 = vertex_map.entry_or_insert(vf).clone();
let vb = edge.absolute_back();
let vertex1 = vertex_map.entry_or_insert(vb).clone();
let curve = curve_mapping(&*edge.curve.lock().unwrap());
Edge::debug_new(&vertex0, &vertex1, curve)
}
}
impl<T, P, C> From<T> for Wire<P, C>
where T: Into<VecDeque<Edge<P, C>>>
{
#[inline(always)]
fn from(edge_list: T) -> Wire<P, C> {
Wire {
edge_list: edge_list.into(),
}
}
}
impl<P, C> FromIterator<Edge<P, C>> for Wire<P, C> {
#[inline(always)]
fn from_iter<I: IntoIterator<Item = Edge<P, C>>>(iter: I) -> Wire<P, C> {
Wire::from(VecDeque::from_iter(iter))
}
}
impl<'a, P, C> FromIterator<&'a Edge<P, C>> for Wire<P, C> {
#[inline(always)]
fn from_iter<I: IntoIterator<Item = &'a Edge<P, C>>>(iter: I) -> Wire<P, C> {
Wire::from(VecDeque::from_iter(iter.into_iter().map(Edge::clone)))
}
}
impl<P, C> IntoIterator for Wire<P, C> {
type Item = Edge<P, C>;
type IntoIter = EdgeIntoIter<P, C>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter { self.edge_list.into_iter() }
}
impl<'a, P, C> IntoIterator for &'a Wire<P, C> {
type Item = &'a Edge<P, C>;
type IntoIter = EdgeIter<'a, P, C>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter { self.edge_list.iter() }
}
/// The reference iterator over all edges in a wire.
pub type EdgeIter<'a, P, C> = vec_deque::Iter<'a, Edge<P, C>>;
/// The mutable reference iterator over all edges in a wire.
pub type EdgeIterMut<'a, P, C> = vec_deque::IterMut<'a, Edge<P, C>>;
/// The into iterator over all edges in a wire.
pub type EdgeIntoIter<P, C> = vec_deque::IntoIter<Edge<P, C>>;
/// The reference parallel iterator over all edges in a wire.
pub type EdgeParallelIter<'a, P, C> = <VecDeque<Edge<P, C>> as IntoParallelRefIterator<'a>>::Iter;
/// The mutable reference parallel iterator over all edges in a wire.
pub type EdgeParallelIterMut<'a, P, C> =
<VecDeque<Edge<P, C>> as IntoParallelRefMutIterator<'a>>::Iter;
/// the parallel iterator over all edges in a wire.
pub type EdgeParallelIntoIter<P, C> = <VecDeque<Edge<P, C>> as IntoParallelIterator>::Iter;
/// The iterator over all the vertices included in a wire.
/// # Details
/// Fundamentally, the iterator runs over all the vertices in a wire.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 6]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// Edge::new(&v[4], &v[5], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next().as_ref(), Some(&v[5]));
/// assert_eq!(viter.next(), None);
/// assert_eq!(viter.next(), None); // VertexIter is a FusedIterator.
/// ```
/// If a pair of adjacent edges share one vertex, the iterator run only one time at the shared vertex.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 6]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[5], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next().as_ref(), Some(&v[5]));
/// assert_eq!(viter.next(), None);
/// ```
/// If the wire is cyclic, the iterator does not arrive at the last vertex.
/// ```
/// # use truck_topology::*;
/// let v = Vertex::news(&[(); 5]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[0], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next(), None);
/// ```
#[derive(Clone, Debug)]
pub struct VertexIter<'a, P, C> {
edge_iter: Peekable<EdgeIter<'a, P, C>>,
unconti_next: Option<Vertex<P>>,
cyclic: bool,
}
impl<'a, P, C> Iterator for VertexIter<'a, P, C> {
type Item = Vertex<P>;
fn next(&mut self) -> Option<Vertex<P>> {
if self.unconti_next.is_some() {
let res = self.unconti_next.clone();
self.unconti_next = None;
res
} else if let Some(edge) = self.edge_iter.next() {
if let Some(next) = self.edge_iter.peek() {
if edge.back() != next.front() {
self.unconti_next = Some(edge.back().clone());
}
} else if !self.cyclic {
self.unconti_next = Some(edge.back().clone());
}
Some(edge.front().clone())
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let min_size = self.edge_iter.len();
let max_size = self.edge_iter.len() * 2;
(min_size, Some(max_size))
}
fn last(self) -> Option<Vertex<P>> {
let closed = self.cyclic;
self.edge_iter.last().map(|edge| {
if closed {
edge.front().clone()
} else {
edge.back().clone()
}
})
}
}
impl<'a, P, C> std::iter::FusedIterator for VertexIter<'a, P, C> {}
impl<P, C> Extend<Edge<P, C>> for Wire<P, C> {
fn extend<T: IntoIterator<Item = Edge<P, C>>>(&mut self, iter: T) {
for edge in iter {
self.push_back(edge);
}
}
}
impl<P, C> std::ops::Deref for Wire<P, C> {
type Target = VecDeque<Edge<P, C>>;
#[inline(always)]
fn deref(&self) -> &Self::Target { &self.edge_list }
}
impl<P, C> std::ops::DerefMut for Wire<P, C> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.edge_list }
}
impl<P, C> Clone for Wire<P, C> {
#[inline(always)]
fn clone(&self) -> Self {
Self {
edge_list: self.edge_list.clone(),
}
}
}
impl<P, C> PartialEq for Wire<P, C> {
#[inline(always)]
fn eq(&self, other: &Self) -> bool { self.edge_list == other.edge_list }
}
impl<P, C> Eq for Wire<P, C> {}
impl<P, C> Default for Wire<P, C> {
#[inline(always)]
fn default() -> Self {
Self {
edge_list: Default::default(),
}
}
}
impl<'a, P: Debug, C: Debug> Debug for DebugDisplay<'a, Wire<P, C>, WireDisplayFormat> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.format {
WireDisplayFormat::EdgesListTuple { edge_format } => f
.debug_tuple("Wire")
.field(&Self {
entity: self.entity,
format: WireDisplayFormat::EdgesList { edge_format },
})
.finish(),
WireDisplayFormat::EdgesList { edge_format } => f
.debug_list()
.entries(
self.entity
.edge_iter()
.map(|edge| edge.display(edge_format)),
)
.finish(),
WireDisplayFormat::VerticesList { vertex_format } => {
let vertices: Vec<_> = self.entity.vertex_iter().collect();
f.debug_list()
.entries(vertices.iter().map(|vertex| vertex.display(vertex_format)))
.finish()
}
}
}
sourcepub fn front_edge(&self) -> Option<&Edge<P, C>>
pub fn front_edge(&self) -> Option<&Edge<P, C>>
Returns the front edge. If self
is empty wire, returns None.
Practically, an alias of the inherited method VecDeque::front()
.
sourcepub fn front_vertex(&self) -> Option<&Vertex<P>>
pub fn front_vertex(&self) -> Option<&Vertex<P>>
Returns the front vertex. If self
is empty wire, returns None.
Examples
use truck_topology::*;
let v = Vertex::news(&[(), (), ()]);
let mut wire = Wire::new();
assert_eq!(wire.front_vertex(), None);
wire.push_back(Edge::new(&v[1], &v[2], ()));
wire.push_front(Edge::new(&v[0], &v[1], ()));
assert_eq!(wire.front_vertex(), Some(&v[0]));
Examples found in repository?
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
pub fn ends_vertices(&self) -> Option<(&Vertex<P>, &Vertex<P>)> {
match (self.front_vertex(), self.back_vertex()) {
(Some(got0), Some(got1)) => Some((got0, got1)),
_ => None,
}
}
/// Moves all the faces of `other` into `self`, leaving `other` empty.
#[inline(always)]
pub fn append(&mut self, other: &mut Wire<P, C>) { self.edge_list.append(&mut other.edge_list) }
/// Splits the `Wire` into two at the given index.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 7]);
/// let mut wire = Wire::new();
/// for i in 0..6 {
/// wire.push_back(Edge::new(&v[i], &v[i + 1], ()));
/// }
/// let original_wire = wire.clone();
/// let mut wire1 = wire.split_off(4);
/// assert_eq!(wire.len(), 4);
/// assert_eq!(wire1.len(), 2);
/// wire.append(&mut wire1);
/// assert_eq!(original_wire, wire);
/// ```
/// # Panics
/// Panics if `at > self.len()`
#[inline(always)]
pub fn split_off(&mut self, at: usize) -> Wire<P, C> {
Wire {
edge_list: self.edge_list.split_off(at),
}
}
/// Inverts the wire.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[3], &v[2], ()),
/// Edge::new(&v[2], &v[1], ()),
/// Edge::new(&v[1], &v[0], ()),
/// ]);
/// wire.invert();
/// for (i, vert) in wire.vertex_iter().enumerate() {
/// assert_eq!(v[i], vert);
/// }
/// ```
#[inline(always)]
pub fn invert(&mut self) -> &mut Self {
*self = self.inverse();
self
}
/// Returns the inverse wire.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[3], &v[2], ()),
/// Edge::new(&v[2], &v[1], ()),
/// Edge::new(&v[1], &v[0], ()),
/// ]);
/// let inverse = wire.inverse();
/// wire.invert();
/// for (edge0, edge1) in wire.edge_iter().zip(inverse.edge_iter()) {
/// assert_eq!(edge0, edge1);
/// }
/// ```
#[inline(always)]
pub fn inverse(&self) -> Wire<P, C> {
let edge_list = self.edge_iter().rev().map(|edge| edge.inverse()).collect();
Wire { edge_list }
}
/// Returns whether all the adjacent pairs of edges have shared vertices or not.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// ]);
/// assert!(!wire.is_continuous());
/// wire.insert(1, Edge::new(&v[1], &v[2], ()));
/// assert!(wire.is_continuous());
/// ```
/// ```
/// use truck_topology::*;
/// // The empty wire is continuous
/// assert!(Wire::<(), ()>::new().is_continuous());
/// ```
pub fn is_continuous(&self) -> bool {
let mut iter = self.edge_iter();
if let Some(edge) = iter.next() {
let mut prev = edge.back();
for edge in iter {
if prev != edge.front() {
return false;
}
prev = edge.back();
}
}
true
}
/// Returns whether the front vertex of the wire is the same as the back one or not.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// ]);
/// assert!(!wire.is_cyclic());
/// wire.push_back(Edge::new(&v[3], &v[0], ()));
/// assert!(wire.is_cyclic());
/// ```
/// ```
/// use truck_topology::*;
/// // The empty wire is cyclic.
/// assert!(Wire::<(), ()>::new().is_cyclic());
/// ```
#[inline(always)]
pub fn is_cyclic(&self) -> bool { self.front_vertex() == self.back_vertex() }
More examples
316 317 318 319 320 321 322 323 324 325 326 327 328
pub fn is_connected(&self) -> bool {
let mut adjacency = self.vertex_adjacency();
// Connecting another boundary of the same face with an edge
for face in self {
for wire in face.boundaries.windows(2) {
let v0 = wire[0].front_vertex().unwrap();
let v1 = wire[1].front_vertex().unwrap();
adjacency.get_mut(&v0.id()).unwrap().push(v1.id());
adjacency.get_mut(&v1.id()).unwrap().push(v0.id());
}
}
check_connectivity(&mut adjacency)
}
sourcepub fn back_edge(&self) -> Option<&Edge<P, C>>
pub fn back_edge(&self) -> Option<&Edge<P, C>>
Returns the back edge. If self
is empty wire, returns None.
Practically, an alias of the inherited method VecDeque::back()
sourcepub fn back_vertex(&self) -> Option<&Vertex<P>>
pub fn back_vertex(&self) -> Option<&Vertex<P>>
Returns the back edge. If self
is empty wire, returns None.
Examples
use truck_topology::*;
let v = Vertex::news(&[(), (), ()]);
let mut wire = Wire::new();
assert_eq!(wire.back_vertex(), None);
wire.push_back(Edge::new(&v[1], &v[2], ()));
wire.push_front(Edge::new(&v[0], &v[1], ()));
assert_eq!(wire.back_vertex(), Some(&v[2]));
Examples found in repository?
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
pub fn ends_vertices(&self) -> Option<(&Vertex<P>, &Vertex<P>)> {
match (self.front_vertex(), self.back_vertex()) {
(Some(got0), Some(got1)) => Some((got0, got1)),
_ => None,
}
}
/// Moves all the faces of `other` into `self`, leaving `other` empty.
#[inline(always)]
pub fn append(&mut self, other: &mut Wire<P, C>) { self.edge_list.append(&mut other.edge_list) }
/// Splits the `Wire` into two at the given index.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 7]);
/// let mut wire = Wire::new();
/// for i in 0..6 {
/// wire.push_back(Edge::new(&v[i], &v[i + 1], ()));
/// }
/// let original_wire = wire.clone();
/// let mut wire1 = wire.split_off(4);
/// assert_eq!(wire.len(), 4);
/// assert_eq!(wire1.len(), 2);
/// wire.append(&mut wire1);
/// assert_eq!(original_wire, wire);
/// ```
/// # Panics
/// Panics if `at > self.len()`
#[inline(always)]
pub fn split_off(&mut self, at: usize) -> Wire<P, C> {
Wire {
edge_list: self.edge_list.split_off(at),
}
}
/// Inverts the wire.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[3], &v[2], ()),
/// Edge::new(&v[2], &v[1], ()),
/// Edge::new(&v[1], &v[0], ()),
/// ]);
/// wire.invert();
/// for (i, vert) in wire.vertex_iter().enumerate() {
/// assert_eq!(v[i], vert);
/// }
/// ```
#[inline(always)]
pub fn invert(&mut self) -> &mut Self {
*self = self.inverse();
self
}
/// Returns the inverse wire.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[3], &v[2], ()),
/// Edge::new(&v[2], &v[1], ()),
/// Edge::new(&v[1], &v[0], ()),
/// ]);
/// let inverse = wire.inverse();
/// wire.invert();
/// for (edge0, edge1) in wire.edge_iter().zip(inverse.edge_iter()) {
/// assert_eq!(edge0, edge1);
/// }
/// ```
#[inline(always)]
pub fn inverse(&self) -> Wire<P, C> {
let edge_list = self.edge_iter().rev().map(|edge| edge.inverse()).collect();
Wire { edge_list }
}
/// Returns whether all the adjacent pairs of edges have shared vertices or not.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// ]);
/// assert!(!wire.is_continuous());
/// wire.insert(1, Edge::new(&v[1], &v[2], ()));
/// assert!(wire.is_continuous());
/// ```
/// ```
/// use truck_topology::*;
/// // The empty wire is continuous
/// assert!(Wire::<(), ()>::new().is_continuous());
/// ```
pub fn is_continuous(&self) -> bool {
let mut iter = self.edge_iter();
if let Some(edge) = iter.next() {
let mut prev = edge.back();
for edge in iter {
if prev != edge.front() {
return false;
}
prev = edge.back();
}
}
true
}
/// Returns whether the front vertex of the wire is the same as the back one or not.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// ]);
/// assert!(!wire.is_cyclic());
/// wire.push_back(Edge::new(&v[3], &v[0], ()));
/// assert!(wire.is_cyclic());
/// ```
/// ```
/// use truck_topology::*;
/// // The empty wire is cyclic.
/// assert!(Wire::<(), ()>::new().is_cyclic());
/// ```
#[inline(always)]
pub fn is_cyclic(&self) -> bool { self.front_vertex() == self.back_vertex() }
sourcepub fn ends_vertices(&self) -> Option<(&Vertex<P>, &Vertex<P>)>
pub fn ends_vertices(&self) -> Option<(&Vertex<P>, &Vertex<P>)>
Returns vertices at both ends.
use truck_topology::*;
let v = Vertex::news(&[(); 3]);
let mut wire = Wire::new();
assert_eq!(wire.back_vertex(), None);
wire.push_back(Edge::new(&v[1], &v[2], ()));
wire.push_front(Edge::new(&v[0], &v[1], ()));
assert_eq!(wire.ends_vertices(), Some((&v[0], &v[2])));
sourcepub fn append(&mut self, other: &mut Wire<P, C>)
pub fn append(&mut self, other: &mut Wire<P, C>)
Moves all the faces of other
into self
, leaving other
empty.
sourcepub fn split_off(&mut self, at: usize) -> Wire<P, C>
pub fn split_off(&mut self, at: usize) -> Wire<P, C>
Splits the Wire
into two at the given index.
Examples
use truck_topology::*;
let v = Vertex::news(&[(); 7]);
let mut wire = Wire::new();
for i in 0..6 {
wire.push_back(Edge::new(&v[i], &v[i + 1], ()));
}
let original_wire = wire.clone();
let mut wire1 = wire.split_off(4);
assert_eq!(wire.len(), 4);
assert_eq!(wire1.len(), 2);
wire.append(&mut wire1);
assert_eq!(original_wire, wire);
Panics
Panics if at > self.len()
Examples found in repository?
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
pub fn cut_by_edge(&self, edge: Edge<P, C>) -> Option<(Self, Self)>
where S: Clone {
if self.boundaries.len() != 1 {
return None;
}
let mut face0 = Face {
boundaries: self.boundaries.clone(),
orientation: self.orientation,
surface: Arc::new(Mutex::new(self.get_surface())),
};
let wire = &mut face0.boundaries[0];
let i = wire
.edge_iter()
.enumerate()
.find(|(_, e)| e.front() == edge.back())
.map(|(i, _)| i)?;
let j = wire
.edge_iter()
.enumerate()
.find(|(_, e)| e.back() == edge.front())
.map(|(i, _)| i)?;
wire.rotate_left(i);
let j = (j + wire.len() - i) % wire.len();
let mut new_wire = wire.split_off(j + 1);
wire.push_back(edge.clone());
new_wire.push_back(edge.inverse());
debug_assert!(Face::try_new(self.boundaries.clone(), ()).is_ok());
debug_assert!(Face::try_new(vec![new_wire.clone()], ()).is_ok());
let face1 = Face {
boundaries: vec![new_wire],
orientation: self.orientation,
surface: Arc::new(Mutex::new(self.get_surface())),
};
Some((face0, face1))
}
sourcepub fn invert(&mut self) -> &mut Self
pub fn invert(&mut self) -> &mut Self
Inverts the wire.
Examples
use truck_topology::*;
let v = Vertex::news(&[(); 4]);
let mut wire = Wire::from(vec![
Edge::new(&v[3], &v[2], ()),
Edge::new(&v[2], &v[1], ()),
Edge::new(&v[1], &v[0], ()),
]);
wire.invert();
for (i, vert) in wire.vertex_iter().enumerate() {
assert_eq!(v[i], vert);
}
Examples found in repository?
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
pub fn try_add_boundary(&mut self, mut wire: Wire<P, C>) -> Result<()>
where S: Clone {
if wire.is_empty() {
return Err(Error::EmptyWire);
} else if !wire.is_closed() {
return Err(Error::NotClosedWire);
} else if !wire.is_simple() {
return Err(Error::NotSimpleWire);
}
if !self.orientation {
wire.invert();
}
self.boundaries.push(wire);
self.renew_pointer();
if !Wire::disjoint_wires(&self.boundaries) {
self.boundaries.pop();
return Err(Error::NotDisjointWires);
}
Ok(())
}
sourcepub fn inverse(&self) -> Wire<P, C>
pub fn inverse(&self) -> Wire<P, C>
Returns the inverse wire.
Examples
use truck_topology::*;
let v = Vertex::news(&[(); 4]);
let mut wire = Wire::from(vec![
Edge::new(&v[3], &v[2], ()),
Edge::new(&v[2], &v[1], ()),
Edge::new(&v[1], &v[0], ()),
]);
let inverse = wire.inverse();
wire.invert();
for (edge0, edge1) in wire.edge_iter().zip(inverse.edge_iter()) {
assert_eq!(edge0, edge1);
}
Examples found in repository?
More examples
sourcepub fn is_continuous(&self) -> bool
pub fn is_continuous(&self) -> bool
Returns whether all the adjacent pairs of edges have shared vertices or not.
Examples
use truck_topology::*;
let v = Vertex::news(&[(); 4]);
let mut wire = Wire::from(vec![
Edge::new(&v[0], &v[1], ()),
Edge::new(&v[2], &v[3], ()),
]);
assert!(!wire.is_continuous());
wire.insert(1, Edge::new(&v[1], &v[2], ()));
assert!(wire.is_continuous());
use truck_topology::*;
// The empty wire is continuous
assert!(Wire::<(), ()>::new().is_continuous());
sourcepub fn is_cyclic(&self) -> bool
pub fn is_cyclic(&self) -> bool
Returns whether the front vertex of the wire is the same as the back one or not.
Examples
use truck_topology::*;
let v = Vertex::news(&[(); 4]);
let mut wire = Wire::from(vec![
Edge::new(&v[0], &v[1], ()),
Edge::new(&v[2], &v[3], ()),
]);
assert!(!wire.is_cyclic());
wire.push_back(Edge::new(&v[3], &v[0], ()));
assert!(wire.is_cyclic());
use truck_topology::*;
// The empty wire is cyclic.
assert!(Wire::<(), ()>::new().is_cyclic());
Examples found in repository?
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
pub fn vertex_iter(&self) -> VertexIter<'_, P, C> {
VertexIter {
edge_iter: self.edge_iter().peekable(),
unconti_next: None,
cyclic: self.is_cyclic(),
}
}
/// Returns the front edge. If `self` is empty wire, returns None.
/// Practically, an alias of the inherited method `VecDeque::front()`.
#[inline(always)]
pub fn front_edge(&self) -> Option<&Edge<P, C>> { self.front() }
/// Returns the front vertex. If `self` is empty wire, returns None.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let mut wire = Wire::new();
/// assert_eq!(wire.front_vertex(), None);
/// wire.push_back(Edge::new(&v[1], &v[2], ()));
/// wire.push_front(Edge::new(&v[0], &v[1], ()));
/// assert_eq!(wire.front_vertex(), Some(&v[0]));
/// ```
#[inline(always)]
pub fn front_vertex(&self) -> Option<&Vertex<P>> { self.front().map(|edge| edge.front()) }
/// Returns the back edge. If `self` is empty wire, returns None.
/// Practically, an alias of the inherited method `VecDeque::back()`
#[inline(always)]
pub fn back_edge(&self) -> Option<&Edge<P, C>> { self.back() }
/// Returns the back edge. If `self` is empty wire, returns None.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let mut wire = Wire::new();
/// assert_eq!(wire.back_vertex(), None);
/// wire.push_back(Edge::new(&v[1], &v[2], ()));
/// wire.push_front(Edge::new(&v[0], &v[1], ()));
/// assert_eq!(wire.back_vertex(), Some(&v[2]));
/// ```
#[inline(always)]
pub fn back_vertex(&self) -> Option<&Vertex<P>> { self.back().map(|edge| edge.back()) }
/// Returns vertices at both ends.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 3]);
/// let mut wire = Wire::new();
/// assert_eq!(wire.back_vertex(), None);
/// wire.push_back(Edge::new(&v[1], &v[2], ()));
/// wire.push_front(Edge::new(&v[0], &v[1], ()));
/// assert_eq!(wire.ends_vertices(), Some((&v[0], &v[2])));
/// ```
#[inline(always)]
pub fn ends_vertices(&self) -> Option<(&Vertex<P>, &Vertex<P>)> {
match (self.front_vertex(), self.back_vertex()) {
(Some(got0), Some(got1)) => Some((got0, got1)),
_ => None,
}
}
/// Moves all the faces of `other` into `self`, leaving `other` empty.
#[inline(always)]
pub fn append(&mut self, other: &mut Wire<P, C>) { self.edge_list.append(&mut other.edge_list) }
/// Splits the `Wire` into two at the given index.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 7]);
/// let mut wire = Wire::new();
/// for i in 0..6 {
/// wire.push_back(Edge::new(&v[i], &v[i + 1], ()));
/// }
/// let original_wire = wire.clone();
/// let mut wire1 = wire.split_off(4);
/// assert_eq!(wire.len(), 4);
/// assert_eq!(wire1.len(), 2);
/// wire.append(&mut wire1);
/// assert_eq!(original_wire, wire);
/// ```
/// # Panics
/// Panics if `at > self.len()`
#[inline(always)]
pub fn split_off(&mut self, at: usize) -> Wire<P, C> {
Wire {
edge_list: self.edge_list.split_off(at),
}
}
/// Inverts the wire.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[3], &v[2], ()),
/// Edge::new(&v[2], &v[1], ()),
/// Edge::new(&v[1], &v[0], ()),
/// ]);
/// wire.invert();
/// for (i, vert) in wire.vertex_iter().enumerate() {
/// assert_eq!(v[i], vert);
/// }
/// ```
#[inline(always)]
pub fn invert(&mut self) -> &mut Self {
*self = self.inverse();
self
}
/// Returns the inverse wire.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[3], &v[2], ()),
/// Edge::new(&v[2], &v[1], ()),
/// Edge::new(&v[1], &v[0], ()),
/// ]);
/// let inverse = wire.inverse();
/// wire.invert();
/// for (edge0, edge1) in wire.edge_iter().zip(inverse.edge_iter()) {
/// assert_eq!(edge0, edge1);
/// }
/// ```
#[inline(always)]
pub fn inverse(&self) -> Wire<P, C> {
let edge_list = self.edge_iter().rev().map(|edge| edge.inverse()).collect();
Wire { edge_list }
}
/// Returns whether all the adjacent pairs of edges have shared vertices or not.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// ]);
/// assert!(!wire.is_continuous());
/// wire.insert(1, Edge::new(&v[1], &v[2], ()));
/// assert!(wire.is_continuous());
/// ```
/// ```
/// use truck_topology::*;
/// // The empty wire is continuous
/// assert!(Wire::<(), ()>::new().is_continuous());
/// ```
pub fn is_continuous(&self) -> bool {
let mut iter = self.edge_iter();
if let Some(edge) = iter.next() {
let mut prev = edge.back();
for edge in iter {
if prev != edge.front() {
return false;
}
prev = edge.back();
}
}
true
}
/// Returns whether the front vertex of the wire is the same as the back one or not.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let mut wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[2], &v[3], ()),
/// ]);
/// assert!(!wire.is_cyclic());
/// wire.push_back(Edge::new(&v[3], &v[0], ()));
/// assert!(wire.is_cyclic());
/// ```
/// ```
/// use truck_topology::*;
/// // The empty wire is cyclic.
/// assert!(Wire::<(), ()>::new().is_cyclic());
/// ```
#[inline(always)]
pub fn is_cyclic(&self) -> bool { self.front_vertex() == self.back_vertex() }
/// Returns whether the wire is closed or not.
/// Here, "closed" means "continuous" and "cyclic".
#[inline(always)]
pub fn is_closed(&self) -> bool { self.is_continuous() && self.is_cyclic() }
sourcepub fn is_closed(&self) -> bool
pub fn is_closed(&self) -> bool
Returns whether the wire is closed or not. Here, “closed” means “continuous” and “cyclic”.
Examples found in repository?
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
pub fn try_new(boundaries: Vec<Wire<P, C>>, surface: S) -> Result<Face<P, C, S>> {
for wire in &boundaries {
if wire.is_empty() {
return Err(Error::EmptyWire);
} else if !wire.is_closed() {
return Err(Error::NotClosedWire);
} else if !wire.is_simple() {
return Err(Error::NotSimpleWire);
}
}
if !Wire::disjoint_wires(&boundaries) {
Err(Error::NotSimpleWire)
} else {
Ok(Face::new_unchecked(boundaries, surface))
}
}
/// Creates a new face by a wire.
/// # Panic
/// All wires in `boundaries` must be non-empty, simple and closed.
#[inline(always)]
pub fn new(boundaries: Vec<Wire<P, C>>, surface: S) -> Face<P, C, S> {
Face::try_new(boundaries, surface).remove_try()
}
/// Creates a new face by a wire.
/// # Remarks
/// This method is prepared only for performance-critical development and is not recommended.
/// This method does NOT check the regularity conditions of `Face::try_new()`.
/// The programmer must guarantee this condition before using this method.
#[inline(always)]
pub fn new_unchecked(boundaries: Vec<Wire<P, C>>, surface: S) -> Face<P, C, S> {
Face {
boundaries,
orientation: true,
surface: Arc::new(Mutex::new(surface)),
}
}
/// Creates a new face by a wire.
/// # Remarks
/// This method check the regularity conditions of `Face::try_new()` in the debug mode.
/// The programmer must guarantee this condition before using this method.
#[inline(always)]
pub fn debug_new(boundaries: Vec<Wire<P, C>>, surface: S) -> Face<P, C, S> {
match cfg!(debug_assertions) {
true => Face::new(boundaries, surface),
false => Face::new_unchecked(boundaries, surface),
}
}
/// Returns the boundaries of the face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 3]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let boundaries = face.boundaries();
/// for (i, vert) in boundaries[0].vertex_iter().enumerate() {
/// assert_eq!(vert, v[i]);
/// }
///
/// // If invert the face, the boundaries is also inverted.
/// face.invert();
/// assert_eq!(boundaries[0].inverse(), face.boundaries()[0]);
/// ```
#[inline(always)]
pub fn boundaries(&self) -> Vec<Wire<P, C>> {
match self.orientation {
true => self.boundaries.clone(),
false => self.boundaries.iter().map(|wire| wire.inverse()).collect(),
}
}
/// Consumes `self` and returns the entity of its boundaries.
/// ```
/// # use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let boundaries = face.clone().into_boundaries();
/// for (i, vert) in boundaries[0].vertex_iter().enumerate() {
/// assert_eq!(vert, v[i]);
/// }
///
/// // If invert the face, the boundaries is also inverted.
/// face.invert();
/// assert_eq!(boundaries[0].inverse(), face.into_boundaries()[0]);
/// ```
#[inline(always)]
pub fn into_boundaries(self) -> Vec<Wire<P, C>> {
match self.orientation {
true => self.boundaries,
false => self.boundaries(),
}
}
/// Returns the reference of the boundaries wire which is generated by constructor.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let boundaries = face.boundaries();
/// face.invert();
///
/// // The result of face.boundary() is already inversed.
/// assert_eq!(face.boundaries()[0], boundaries[0].inverse());
///
/// // The absolute boundaries does never change.
/// assert_eq!(face.absolute_boundaries(), &boundaries);
/// ```
#[inline(always)]
pub const fn absolute_boundaries(&self) -> &Vec<Wire<P, C>> { &self.boundaries }
/// Returns a clone of the face without inversion.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let face0 = Face::new(vec![wire], ());
/// let face1 = face0.inverse();
/// let face2 = face1.absolute_clone();
/// assert_eq!(face0, face2);
/// assert_ne!(face1, face2);
/// assert!(face1.is_same(&face2));
/// ```
#[inline(always)]
pub fn absolute_clone(&self) -> Self {
Self {
boundaries: self.boundaries.clone(),
surface: Arc::clone(&self.surface),
orientation: true,
}
}
/// Returns an iterator over all edges in the boundaries.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// face.invert();
/// let boundaries = face.boundaries().clone();
/// let edge_iter0 = boundaries.iter().flat_map(Wire::edge_iter);
/// let edge_iter1 = face.boundary_iters().into_iter().flatten();
/// for (edge0, edge1) in edge_iter0.zip(edge_iter1) {
/// assert_eq!(edge0, &edge1);
/// }
/// ```
#[inline(always)]
pub fn boundary_iters(&self) -> Vec<BoundaryIter<'_, P, C>> {
self.boundaries
.iter()
.map(|wire| BoundaryIter {
edge_iter: wire.edge_iter(),
orientation: self.orientation,
})
.collect()
}
#[inline(always)]
fn renew_pointer(&mut self)
where S: Clone {
let surface = self.get_surface();
self.surface = Arc::new(Mutex::new(surface));
}
/// Returns an iterator over the edges.
#[inline(always)]
pub fn edge_iter(&self) -> impl Iterator<Item = Edge<P, C>> + '_ {
self.boundary_iters().into_iter().flatten()
}
/// Returns an iterator over the vertices.
#[inline(always)]
pub fn vertex_iter(&self) -> impl Iterator<Item = Vertex<P>> + '_ {
self.edge_iter().map(|e| e.front().clone())
}
/// Adds a boundary to the face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[5], ()),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face0 = Face::new(vec![wire0.clone()], ());
/// face0.try_add_boundary(wire1.clone()).unwrap();
/// let face1 = Face::new(vec![wire0, wire1], ());
/// assert_eq!(face0.boundaries(), face1.boundaries());
/// ```
/// # Remarks
/// 1. If the face is inverted, then the added wire is inverted as absolute boundary.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[5], &v[4], ()).inverse(),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face = Face::new(vec![wire0], ());
/// face.invert();
/// face.try_add_boundary(wire1.clone()).unwrap();
///
/// // The boundary is added in compatible with the face orientation.
/// assert_eq!(face.boundaries()[1], wire1);
///
/// // The absolute boundary is inverted!
/// let iter0 = face.absolute_boundaries()[1].edge_iter();
/// let iter1 = wire1.edge_iter().rev();
/// for (edge0, edge1) in iter0.zip(iter1) {
/// assert_eq!(edge0.id(), edge1.id());
/// assert_eq!(edge0.orientation(), !edge1.orientation());
/// }
/// ```
/// 2. This method renew the face id.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[5], &v[4], ()).inverse(),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face0 = Face::new(vec![wire0], ());
/// let face1 = face0.clone();
/// assert_eq!(face0.id(), face1.id());
/// face0.try_add_boundary(wire1).unwrap();
/// assert_ne!(face0.id(), face1.id());
/// ```
#[inline(always)]
pub fn try_add_boundary(&mut self, mut wire: Wire<P, C>) -> Result<()>
where S: Clone {
if wire.is_empty() {
return Err(Error::EmptyWire);
} else if !wire.is_closed() {
return Err(Error::NotClosedWire);
} else if !wire.is_simple() {
return Err(Error::NotSimpleWire);
}
if !self.orientation {
wire.invert();
}
self.boundaries.push(wire);
self.renew_pointer();
if !Wire::disjoint_wires(&self.boundaries) {
self.boundaries.pop();
return Err(Error::NotDisjointWires);
}
Ok(())
}
sourcepub fn is_simple(&self) -> bool
pub fn is_simple(&self) -> bool
Returns whether simple or not. Here, “simple” means all the vertices in the wire are shared from only two edges at most.
Examples
use truck_topology::*;
let v = Vertex::news(&[(); 4]);
let edge0 = Edge::new(&v[0], &v[1], ());
let edge1 = Edge::new(&v[1], &v[2], ());
let edge2 = Edge::new(&v[2], &v[3], ());
let edge3 = Edge::new(&v[3], &v[1], ());
let edge4 = Edge::new(&v[3], &v[0], ());
let wire0 = Wire::from_iter(vec![&edge0, &edge1, &edge2, &edge3]);
let wire1 = Wire::from(vec![edge0, edge1, edge2, edge4]);
assert!(!wire0.is_simple());
assert!(wire1.is_simple());
use truck_topology::*;
// The empty wire is simple.
assert!(Wire::<(), ()>::new().is_simple());
Examples found in repository?
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
pub fn try_new(boundaries: Vec<Wire<P, C>>, surface: S) -> Result<Face<P, C, S>> {
for wire in &boundaries {
if wire.is_empty() {
return Err(Error::EmptyWire);
} else if !wire.is_closed() {
return Err(Error::NotClosedWire);
} else if !wire.is_simple() {
return Err(Error::NotSimpleWire);
}
}
if !Wire::disjoint_wires(&boundaries) {
Err(Error::NotSimpleWire)
} else {
Ok(Face::new_unchecked(boundaries, surface))
}
}
/// Creates a new face by a wire.
/// # Panic
/// All wires in `boundaries` must be non-empty, simple and closed.
#[inline(always)]
pub fn new(boundaries: Vec<Wire<P, C>>, surface: S) -> Face<P, C, S> {
Face::try_new(boundaries, surface).remove_try()
}
/// Creates a new face by a wire.
/// # Remarks
/// This method is prepared only for performance-critical development and is not recommended.
/// This method does NOT check the regularity conditions of `Face::try_new()`.
/// The programmer must guarantee this condition before using this method.
#[inline(always)]
pub fn new_unchecked(boundaries: Vec<Wire<P, C>>, surface: S) -> Face<P, C, S> {
Face {
boundaries,
orientation: true,
surface: Arc::new(Mutex::new(surface)),
}
}
/// Creates a new face by a wire.
/// # Remarks
/// This method check the regularity conditions of `Face::try_new()` in the debug mode.
/// The programmer must guarantee this condition before using this method.
#[inline(always)]
pub fn debug_new(boundaries: Vec<Wire<P, C>>, surface: S) -> Face<P, C, S> {
match cfg!(debug_assertions) {
true => Face::new(boundaries, surface),
false => Face::new_unchecked(boundaries, surface),
}
}
/// Returns the boundaries of the face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 3]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let boundaries = face.boundaries();
/// for (i, vert) in boundaries[0].vertex_iter().enumerate() {
/// assert_eq!(vert, v[i]);
/// }
///
/// // If invert the face, the boundaries is also inverted.
/// face.invert();
/// assert_eq!(boundaries[0].inverse(), face.boundaries()[0]);
/// ```
#[inline(always)]
pub fn boundaries(&self) -> Vec<Wire<P, C>> {
match self.orientation {
true => self.boundaries.clone(),
false => self.boundaries.iter().map(|wire| wire.inverse()).collect(),
}
}
/// Consumes `self` and returns the entity of its boundaries.
/// ```
/// # use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let boundaries = face.clone().into_boundaries();
/// for (i, vert) in boundaries[0].vertex_iter().enumerate() {
/// assert_eq!(vert, v[i]);
/// }
///
/// // If invert the face, the boundaries is also inverted.
/// face.invert();
/// assert_eq!(boundaries[0].inverse(), face.into_boundaries()[0]);
/// ```
#[inline(always)]
pub fn into_boundaries(self) -> Vec<Wire<P, C>> {
match self.orientation {
true => self.boundaries,
false => self.boundaries(),
}
}
/// Returns the reference of the boundaries wire which is generated by constructor.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let boundaries = face.boundaries();
/// face.invert();
///
/// // The result of face.boundary() is already inversed.
/// assert_eq!(face.boundaries()[0], boundaries[0].inverse());
///
/// // The absolute boundaries does never change.
/// assert_eq!(face.absolute_boundaries(), &boundaries);
/// ```
#[inline(always)]
pub const fn absolute_boundaries(&self) -> &Vec<Wire<P, C>> { &self.boundaries }
/// Returns a clone of the face without inversion.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let face0 = Face::new(vec![wire], ());
/// let face1 = face0.inverse();
/// let face2 = face1.absolute_clone();
/// assert_eq!(face0, face2);
/// assert_ne!(face1, face2);
/// assert!(face1.is_same(&face2));
/// ```
#[inline(always)]
pub fn absolute_clone(&self) -> Self {
Self {
boundaries: self.boundaries.clone(),
surface: Arc::clone(&self.surface),
orientation: true,
}
}
/// Returns an iterator over all edges in the boundaries.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// face.invert();
/// let boundaries = face.boundaries().clone();
/// let edge_iter0 = boundaries.iter().flat_map(Wire::edge_iter);
/// let edge_iter1 = face.boundary_iters().into_iter().flatten();
/// for (edge0, edge1) in edge_iter0.zip(edge_iter1) {
/// assert_eq!(edge0, &edge1);
/// }
/// ```
#[inline(always)]
pub fn boundary_iters(&self) -> Vec<BoundaryIter<'_, P, C>> {
self.boundaries
.iter()
.map(|wire| BoundaryIter {
edge_iter: wire.edge_iter(),
orientation: self.orientation,
})
.collect()
}
#[inline(always)]
fn renew_pointer(&mut self)
where S: Clone {
let surface = self.get_surface();
self.surface = Arc::new(Mutex::new(surface));
}
/// Returns an iterator over the edges.
#[inline(always)]
pub fn edge_iter(&self) -> impl Iterator<Item = Edge<P, C>> + '_ {
self.boundary_iters().into_iter().flatten()
}
/// Returns an iterator over the vertices.
#[inline(always)]
pub fn vertex_iter(&self) -> impl Iterator<Item = Vertex<P>> + '_ {
self.edge_iter().map(|e| e.front().clone())
}
/// Adds a boundary to the face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[5], ()),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face0 = Face::new(vec![wire0.clone()], ());
/// face0.try_add_boundary(wire1.clone()).unwrap();
/// let face1 = Face::new(vec![wire0, wire1], ());
/// assert_eq!(face0.boundaries(), face1.boundaries());
/// ```
/// # Remarks
/// 1. If the face is inverted, then the added wire is inverted as absolute boundary.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[5], &v[4], ()).inverse(),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face = Face::new(vec![wire0], ());
/// face.invert();
/// face.try_add_boundary(wire1.clone()).unwrap();
///
/// // The boundary is added in compatible with the face orientation.
/// assert_eq!(face.boundaries()[1], wire1);
///
/// // The absolute boundary is inverted!
/// let iter0 = face.absolute_boundaries()[1].edge_iter();
/// let iter1 = wire1.edge_iter().rev();
/// for (edge0, edge1) in iter0.zip(iter1) {
/// assert_eq!(edge0.id(), edge1.id());
/// assert_eq!(edge0.orientation(), !edge1.orientation());
/// }
/// ```
/// 2. This method renew the face id.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[5], &v[4], ()).inverse(),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face0 = Face::new(vec![wire0], ());
/// let face1 = face0.clone();
/// assert_eq!(face0.id(), face1.id());
/// face0.try_add_boundary(wire1).unwrap();
/// assert_ne!(face0.id(), face1.id());
/// ```
#[inline(always)]
pub fn try_add_boundary(&mut self, mut wire: Wire<P, C>) -> Result<()>
where S: Clone {
if wire.is_empty() {
return Err(Error::EmptyWire);
} else if !wire.is_closed() {
return Err(Error::NotClosedWire);
} else if !wire.is_simple() {
return Err(Error::NotSimpleWire);
}
if !self.orientation {
wire.invert();
}
self.boundaries.push(wire);
self.renew_pointer();
if !Wire::disjoint_wires(&self.boundaries) {
self.boundaries.pop();
return Err(Error::NotDisjointWires);
}
Ok(())
}
sourcepub fn disjoint_wires(wires: &[Wire<P, C>]) -> bool
pub fn disjoint_wires(wires: &[Wire<P, C>]) -> bool
Determines whether all the wires in wires
has no same vertices.
Examples
use truck_topology::*;
let v = Vertex::news(&[(), (), (), (), ()]);
let edge0 = Edge::new(&v[0], &v[1], ());
let edge1 = Edge::new(&v[1], &v[2], ());
let edge2 = Edge::new(&v[2], &v[3], ());
let edge3 = Edge::new(&v[3], &v[4], ());
let wire0 = Wire::from(vec![edge0, edge1]);
let wire1 = Wire::from(vec![edge2]);
let wire2 = Wire::from(vec![edge3]);
assert!(Wire::disjoint_wires(&[wire0.clone(), wire2]));
assert!(!Wire::disjoint_wires(&[wire0, wire1]));
Examples found in repository?
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
pub fn try_new(boundaries: Vec<Wire<P, C>>, surface: S) -> Result<Face<P, C, S>> {
for wire in &boundaries {
if wire.is_empty() {
return Err(Error::EmptyWire);
} else if !wire.is_closed() {
return Err(Error::NotClosedWire);
} else if !wire.is_simple() {
return Err(Error::NotSimpleWire);
}
}
if !Wire::disjoint_wires(&boundaries) {
Err(Error::NotSimpleWire)
} else {
Ok(Face::new_unchecked(boundaries, surface))
}
}
/// Creates a new face by a wire.
/// # Panic
/// All wires in `boundaries` must be non-empty, simple and closed.
#[inline(always)]
pub fn new(boundaries: Vec<Wire<P, C>>, surface: S) -> Face<P, C, S> {
Face::try_new(boundaries, surface).remove_try()
}
/// Creates a new face by a wire.
/// # Remarks
/// This method is prepared only for performance-critical development and is not recommended.
/// This method does NOT check the regularity conditions of `Face::try_new()`.
/// The programmer must guarantee this condition before using this method.
#[inline(always)]
pub fn new_unchecked(boundaries: Vec<Wire<P, C>>, surface: S) -> Face<P, C, S> {
Face {
boundaries,
orientation: true,
surface: Arc::new(Mutex::new(surface)),
}
}
/// Creates a new face by a wire.
/// # Remarks
/// This method check the regularity conditions of `Face::try_new()` in the debug mode.
/// The programmer must guarantee this condition before using this method.
#[inline(always)]
pub fn debug_new(boundaries: Vec<Wire<P, C>>, surface: S) -> Face<P, C, S> {
match cfg!(debug_assertions) {
true => Face::new(boundaries, surface),
false => Face::new_unchecked(boundaries, surface),
}
}
/// Returns the boundaries of the face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 3]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let boundaries = face.boundaries();
/// for (i, vert) in boundaries[0].vertex_iter().enumerate() {
/// assert_eq!(vert, v[i]);
/// }
///
/// // If invert the face, the boundaries is also inverted.
/// face.invert();
/// assert_eq!(boundaries[0].inverse(), face.boundaries()[0]);
/// ```
#[inline(always)]
pub fn boundaries(&self) -> Vec<Wire<P, C>> {
match self.orientation {
true => self.boundaries.clone(),
false => self.boundaries.iter().map(|wire| wire.inverse()).collect(),
}
}
/// Consumes `self` and returns the entity of its boundaries.
/// ```
/// # use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let boundaries = face.clone().into_boundaries();
/// for (i, vert) in boundaries[0].vertex_iter().enumerate() {
/// assert_eq!(vert, v[i]);
/// }
///
/// // If invert the face, the boundaries is also inverted.
/// face.invert();
/// assert_eq!(boundaries[0].inverse(), face.into_boundaries()[0]);
/// ```
#[inline(always)]
pub fn into_boundaries(self) -> Vec<Wire<P, C>> {
match self.orientation {
true => self.boundaries,
false => self.boundaries(),
}
}
/// Returns the reference of the boundaries wire which is generated by constructor.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// let boundaries = face.boundaries();
/// face.invert();
///
/// // The result of face.boundary() is already inversed.
/// assert_eq!(face.boundaries()[0], boundaries[0].inverse());
///
/// // The absolute boundaries does never change.
/// assert_eq!(face.absolute_boundaries(), &boundaries);
/// ```
#[inline(always)]
pub const fn absolute_boundaries(&self) -> &Vec<Wire<P, C>> { &self.boundaries }
/// Returns a clone of the face without inversion.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let face0 = Face::new(vec![wire], ());
/// let face1 = face0.inverse();
/// let face2 = face1.absolute_clone();
/// assert_eq!(face0, face2);
/// assert_ne!(face1, face2);
/// assert!(face1.is_same(&face2));
/// ```
#[inline(always)]
pub fn absolute_clone(&self) -> Self {
Self {
boundaries: self.boundaries.clone(),
surface: Arc::clone(&self.surface),
orientation: true,
}
}
/// Returns an iterator over all edges in the boundaries.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), ()]);
/// let wire = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let mut face = Face::new(vec![wire], ());
/// face.invert();
/// let boundaries = face.boundaries().clone();
/// let edge_iter0 = boundaries.iter().flat_map(Wire::edge_iter);
/// let edge_iter1 = face.boundary_iters().into_iter().flatten();
/// for (edge0, edge1) in edge_iter0.zip(edge_iter1) {
/// assert_eq!(edge0, &edge1);
/// }
/// ```
#[inline(always)]
pub fn boundary_iters(&self) -> Vec<BoundaryIter<'_, P, C>> {
self.boundaries
.iter()
.map(|wire| BoundaryIter {
edge_iter: wire.edge_iter(),
orientation: self.orientation,
})
.collect()
}
#[inline(always)]
fn renew_pointer(&mut self)
where S: Clone {
let surface = self.get_surface();
self.surface = Arc::new(Mutex::new(surface));
}
/// Returns an iterator over the edges.
#[inline(always)]
pub fn edge_iter(&self) -> impl Iterator<Item = Edge<P, C>> + '_ {
self.boundary_iters().into_iter().flatten()
}
/// Returns an iterator over the vertices.
#[inline(always)]
pub fn vertex_iter(&self) -> impl Iterator<Item = Vertex<P>> + '_ {
self.edge_iter().map(|e| e.front().clone())
}
/// Adds a boundary to the face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[4], &v[5], ()),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face0 = Face::new(vec![wire0.clone()], ());
/// face0.try_add_boundary(wire1.clone()).unwrap();
/// let face1 = Face::new(vec![wire0, wire1], ());
/// assert_eq!(face0.boundaries(), face1.boundaries());
/// ```
/// # Remarks
/// 1. If the face is inverted, then the added wire is inverted as absolute boundary.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[5], &v[4], ()).inverse(),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face = Face::new(vec![wire0], ());
/// face.invert();
/// face.try_add_boundary(wire1.clone()).unwrap();
///
/// // The boundary is added in compatible with the face orientation.
/// assert_eq!(face.boundaries()[1], wire1);
///
/// // The absolute boundary is inverted!
/// let iter0 = face.absolute_boundaries()[1].edge_iter();
/// let iter1 = wire1.edge_iter().rev();
/// for (edge0, edge1) in iter0.zip(iter1) {
/// assert_eq!(edge0.id(), edge1.id());
/// assert_eq!(edge0.orientation(), !edge1.orientation());
/// }
/// ```
/// 2. This method renew the face id.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(), (), (), (), (), ()]);
/// let wire0 = Wire::from(vec![
/// Edge::new(&v[0], &v[1], ()),
/// Edge::new(&v[1], &v[2], ()),
/// Edge::new(&v[2], &v[0], ()),
/// ]);
/// let wire1 = Wire::from(vec![
/// Edge::new(&v[3], &v[4], ()),
/// Edge::new(&v[5], &v[4], ()).inverse(),
/// Edge::new(&v[5], &v[3], ()),
/// ]);
/// let mut face0 = Face::new(vec![wire0], ());
/// let face1 = face0.clone();
/// assert_eq!(face0.id(), face1.id());
/// face0.try_add_boundary(wire1).unwrap();
/// assert_ne!(face0.id(), face1.id());
/// ```
#[inline(always)]
pub fn try_add_boundary(&mut self, mut wire: Wire<P, C>) -> Result<()>
where S: Clone {
if wire.is_empty() {
return Err(Error::EmptyWire);
} else if !wire.is_closed() {
return Err(Error::NotClosedWire);
} else if !wire.is_simple() {
return Err(Error::NotSimpleWire);
}
if !self.orientation {
wire.invert();
}
self.boundaries.push(wire);
self.renew_pointer();
if !Wire::disjoint_wires(&self.boundaries) {
self.boundaries.pop();
return Err(Error::NotDisjointWires);
}
Ok(())
}
sourcepub fn swap_edge_into_wire(&mut self, idx: usize, wire: Wire<P, C>) -> bool
pub fn swap_edge_into_wire(&mut self, idx: usize, wire: Wire<P, C>) -> bool
Swap one edge into two edges.
Arguments
idx
: Index of edge in wireedges
: Inserted edges
Examples
use truck_topology::*;
let v = Vertex::news(&[(), (), (), (), ()]);
let edge0 = Edge::new(&v[0], &v[1], 0);
let edge1 = Edge::new(&v[1], &v[3], 1);
let edge2 = Edge::new(&v[3], &v[4], 2);
let edge3 = Edge::new(&v[1], &v[2], 3);
let edge4 = Edge::new(&v[2], &v[3], 4);
let mut wire0 = Wire::from(vec![
edge0.clone(), edge1, edge2.clone()
]);
let wire1 = Wire::from(vec![
edge0, edge3.clone(), edge4.clone(), edge2
]);
assert_ne!(wire0, wire1);
wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4]));
assert_eq!(wire0, wire1);
Panics
Panic occars if idx >= self.len()
.
Failure
Returns false
and self
will not be changed if the end vertices of self[idx]
and the ones of wire
is not the same.
use truck_topology::*;
let v = Vertex::news(&[(), (), (), (), ()]);
let edge0 = Edge::new(&v[0], &v[1], 0);
let edge1 = Edge::new(&v[1], &v[3], 1);
let edge2 = Edge::new(&v[3], &v[4], 2);
let edge3 = Edge::new(&v[1], &v[2], 3);
let edge4 = Edge::new(&v[2], &v[1], 4);
let mut wire0 = Wire::from(vec![
edge0.clone(), edge1, edge2.clone()
]);
let backup = wire0.clone();
// The end vertices of wire[1] == edge1 is (v[1], v[3]).
// The end points of new wire [edge3, edge4] is (v[1], v[1]).
// Since the back vertices are different, returns false and do nothing.
assert!(!wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4])));
assert_eq!(wire0, backup);
Examples found in repository?
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
pub fn cut_edge(
&mut self,
edge_id: EdgeID<C>,
vertex: &Vertex<P>,
) -> Option<(Edge<P, C>, Edge<P, C>)>
where
P: Clone,
C: Cut<Point = P> + SearchParameter<D1, Point = P>,
{
if self.vertex_iter().any(|v| &v == vertex) {
return None;
}
let mut edges = None;
self.iter_mut()
.flat_map(|face| face.boundaries.iter_mut())
.try_for_each(|wire| {
let find_res = wire
.iter()
.enumerate()
.find(|(_, edge)| edge.id() == edge_id);
let (idx, edge) = match find_res {
Some(got) => got,
None => return Some(()),
};
if edges.is_none() {
edges = Some(edge.absolute_clone().cut(vertex)?);
}
let edges = edges.as_ref().unwrap();
let new_wire = match edge.orientation() {
true => Wire::from(vec![edges.0.clone(), edges.1.clone()]),
false => Wire::from(vec![edges.1.inverse(), edges.0.inverse()]),
};
let flag = wire.swap_edge_into_wire(idx, new_wire);
debug_assert!(flag);
Some(())
});
edges
}
sourcepub fn is_geometric_consistent(&self) -> boolwhere
P: Tolerance,
C: BoundedCurve<Point = P>,
pub fn is_geometric_consistent(&self) -> boolwhere
P: Tolerance,
C: BoundedCurve<Point = P>,
Returns the consistence of the geometry of end vertices and the geometry of edge.
sourcepub fn display(
&self,
format: WireDisplayFormat
) -> DebugDisplay<'_, Self, WireDisplayFormat>
pub fn display(
&self,
format: WireDisplayFormat
) -> DebugDisplay<'_, Self, WireDisplayFormat>
Creates display struct for debugging the wire.
Examples
use truck_topology::*;
use WireDisplayFormat as WDF;
let v = Vertex::news(&[0, 1, 2, 3, 4]);
let wire: Wire<usize, usize> = vec![
Edge::new(&v[0], &v[1], 100),
Edge::new(&v[2], &v[1], 110).inverse(),
Edge::new(&v[3], &v[4], 120),
].into();
let vertex_format = VertexDisplayFormat::AsPoint;
let edge_format = EdgeDisplayFormat::VerticesTuple { vertex_format };
assert_eq!(
&format!("{:?}", wire.display(WDF::EdgesListTuple {edge_format})),
"Wire([(0, 1), (1, 2), (3, 4)])",
);
assert_eq!(
&format!("{:?}", wire.display(WDF::EdgesList {edge_format})),
"[(0, 1), (1, 2), (3, 4)]",
);
assert_eq!(
&format!("{:?}", wire.display(WDF::VerticesList {vertex_format})),
"[0, 1, 2, 3, 4]",
);
Examples found in repository?
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.format {
FaceDisplayFormat::Full { wire_format } => f
.debug_struct("Face")
.field("id", &self.entity.id())
.field(
"boundaries",
&self
.entity
.boundaries()
.iter()
.map(|wire| wire.display(wire_format))
.collect::<Vec<_>>(),
)
.field("entity", &MutexFmt(&self.entity.surface))
.finish(),
FaceDisplayFormat::BoundariesAndID { wire_format } => f
.debug_struct("Face")
.field("id", &self.entity.id())
.field(
"boundaries",
&self
.entity
.boundaries()
.iter()
.map(|wire| wire.display(wire_format))
.collect::<Vec<_>>(),
)
.finish(),
FaceDisplayFormat::BoundariesAndSurface { wire_format } => f
.debug_struct("Face")
.field(
"boundaries",
&self
.entity
.boundaries()
.iter()
.map(|wire| wire.display(wire_format))
.collect::<Vec<_>>(),
)
.field("entity", &MutexFmt(&self.entity.surface))
.finish(),
FaceDisplayFormat::LoopsListTuple { wire_format } => f
.debug_tuple("Face")
.field(
&self
.entity
.boundaries()
.iter()
.map(|wire| wire.display(wire_format))
.collect::<Vec<_>>(),
)
.finish(),
FaceDisplayFormat::LoopsList { wire_format } => f
.debug_list()
.entries(
self.entity
.boundaries()
.iter()
.map(|wire| wire.display(wire_format)),
)
.finish(),
FaceDisplayFormat::AsSurface => {
f.write_fmt(format_args!("{:?}", &MutexFmt(&self.entity.surface)))
}
}
}
Methods from Deref<Target = VecDeque<Edge<P, C>>>§
1.0.0 · sourcepub fn get(&self, index: usize) -> Option<&T>
pub fn get(&self, index: usize) -> Option<&T>
Provides a reference to the element at the given index.
Element at index 0 is the front of the queue.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(3);
buf.push_back(4);
buf.push_back(5);
assert_eq!(buf.get(1), Some(&4));
1.0.0 · sourcepub fn get_mut(&mut self, index: usize) -> Option<&mut T>
pub fn get_mut(&mut self, index: usize) -> Option<&mut T>
Provides a mutable reference to the element at the given index.
Element at index 0 is the front of the queue.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(3);
buf.push_back(4);
buf.push_back(5);
if let Some(elem) = buf.get_mut(1) {
*elem = 7;
}
assert_eq!(buf[1], 7);
1.0.0 · sourcepub fn swap(&mut self, i: usize, j: usize)
pub fn swap(&mut self, i: usize, j: usize)
Swaps elements at indices i
and j
.
i
and j
may be equal.
Element at index 0 is the front of the queue.
Panics
Panics if either index is out of bounds.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(3);
buf.push_back(4);
buf.push_back(5);
assert_eq!(buf, [3, 4, 5]);
buf.swap(0, 2);
assert_eq!(buf, [5, 4, 3]);
1.0.0 · sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of elements the deque can hold without reallocating.
Examples
use std::collections::VecDeque;
let buf: VecDeque<i32> = VecDeque::with_capacity(10);
assert!(buf.capacity() >= 10);
1.0.0 · sourcepub fn reserve_exact(&mut self, additional: usize)
pub fn reserve_exact(&mut self, additional: usize)
Reserves the minimum capacity for at least additional
more elements to be inserted in the
given deque. Does nothing if the capacity is already sufficient.
Note that the allocator may give the collection more space than it requests. Therefore
capacity can not be relied upon to be precisely minimal. Prefer reserve
if future
insertions are expected.
Panics
Panics if the new capacity overflows usize
.
Examples
use std::collections::VecDeque;
let mut buf: VecDeque<i32> = [1].into();
buf.reserve_exact(10);
assert!(buf.capacity() >= 11);
1.0.0 · sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional
more elements to be inserted in the given
deque. The collection may reserve more space to speculatively avoid frequent reallocations.
Panics
Panics if the new capacity overflows usize
.
Examples
use std::collections::VecDeque;
let mut buf: VecDeque<i32> = [1].into();
buf.reserve(10);
assert!(buf.capacity() >= 11);
1.57.0 · sourcepub fn try_reserve_exact(
&mut self,
additional: usize
) -> Result<(), TryReserveError>
pub fn try_reserve_exact(
&mut self,
additional: usize
) -> Result<(), TryReserveError>
Tries to reserve the minimum capacity for at least additional
more elements to
be inserted in the given deque. After calling try_reserve_exact
,
capacity will be greater than or equal to self.len() + additional
if
it returns Ok(())
. Does nothing if the capacity is already sufficient.
Note that the allocator may give the collection more space than it
requests. Therefore, capacity can not be relied upon to be precisely
minimal. Prefer try_reserve
if future insertions are expected.
Errors
If the capacity overflows usize
, or the allocator reports a failure, then an error
is returned.
Examples
use std::collections::TryReserveError;
use std::collections::VecDeque;
fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
let mut output = VecDeque::new();
// Pre-reserve the memory, exiting if we can't
output.try_reserve_exact(data.len())?;
// Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
output.extend(data.iter().map(|&val| {
val * 2 + 5 // very complicated
}));
Ok(output)
}
1.57.0 · sourcepub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
Tries to reserve capacity for at least additional
more elements to be inserted
in the given deque. The collection may reserve more space to speculatively avoid
frequent reallocations. After calling try_reserve
, capacity will be
greater than or equal to self.len() + additional
if it returns
Ok(())
. Does nothing if capacity is already sufficient. This method
preserves the contents even if an error occurs.
Errors
If the capacity overflows usize
, or the allocator reports a failure, then an error
is returned.
Examples
use std::collections::TryReserveError;
use std::collections::VecDeque;
fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
let mut output = VecDeque::new();
// Pre-reserve the memory, exiting if we can't
output.try_reserve(data.len())?;
// Now we know this can't OOM in the middle of our complex work
output.extend(data.iter().map(|&val| {
val * 2 + 5 // very complicated
}));
Ok(output)
}
1.5.0 · sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Shrinks the capacity of the deque as much as possible.
It will drop down as close as possible to the length but the allocator may still inform the deque that there is space for a few more elements.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::with_capacity(15);
buf.extend(0..4);
assert_eq!(buf.capacity(), 15);
buf.shrink_to_fit();
assert!(buf.capacity() >= 4);
1.56.0 · sourcepub fn shrink_to(&mut self, min_capacity: usize)
pub fn shrink_to(&mut self, min_capacity: usize)
Shrinks the capacity of the deque with a lower bound.
The capacity will remain at least as large as both the length and the supplied value.
If the current capacity is less than the lower limit, this is a no-op.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::with_capacity(15);
buf.extend(0..4);
assert_eq!(buf.capacity(), 15);
buf.shrink_to(6);
assert!(buf.capacity() >= 6);
buf.shrink_to(0);
assert!(buf.capacity() >= 4);
1.16.0 · sourcepub fn truncate(&mut self, len: usize)
pub fn truncate(&mut self, len: usize)
Shortens the deque, keeping the first len
elements and dropping
the rest.
If len
is greater than the deque’s current length, this has no
effect.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(5);
buf.push_back(10);
buf.push_back(15);
assert_eq!(buf, [5, 10, 15]);
buf.truncate(1);
assert_eq!(buf, [5]);
sourcepub fn allocator(&self) -> &A
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn allocator(&self) -> &A
allocator_api
)Returns a reference to the underlying allocator.
1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
pub fn iter(&self) -> Iter<'_, T>
Returns a front-to-back iterator.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(5);
buf.push_back(3);
buf.push_back(4);
let b: &[_] = &[&5, &3, &4];
let c: Vec<&i32> = buf.iter().collect();
assert_eq!(&c[..], b);
1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
pub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a front-to-back iterator that returns mutable references.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(5);
buf.push_back(3);
buf.push_back(4);
for num in buf.iter_mut() {
*num = *num - 2;
}
let b: &[_] = &[&mut 3, &mut 1, &mut 2];
assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1.5.0 · sourcepub fn as_slices(&self) -> (&[T], &[T])
pub fn as_slices(&self) -> (&[T], &[T])
Returns a pair of slices which contain, in order, the contents of the deque.
If make_contiguous
was previously called, all elements of the
deque will be in the first slice and the second slice will be empty.
Examples
use std::collections::VecDeque;
let mut deque = VecDeque::new();
deque.push_back(0);
deque.push_back(1);
deque.push_back(2);
assert_eq!(deque.as_slices(), (&[0, 1, 2][..], &[][..]));
deque.push_front(10);
deque.push_front(9);
assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1.5.0 · sourcepub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T])
pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T])
Returns a pair of slices which contain, in order, the contents of the deque.
If make_contiguous
was previously called, all elements of the
deque will be in the first slice and the second slice will be empty.
Examples
use std::collections::VecDeque;
let mut deque = VecDeque::new();
deque.push_back(0);
deque.push_back(1);
deque.push_front(10);
deque.push_front(9);
deque.as_mut_slices().0[0] = 42;
deque.as_mut_slices().1[0] = 24;
assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..]));
1.0.0 · sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the deque.
Examples
use std::collections::VecDeque;
let mut deque = VecDeque::new();
assert_eq!(deque.len(), 0);
deque.push_back(1);
assert_eq!(deque.len(), 1);
1.0.0 · sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if the deque is empty.
Examples
use std::collections::VecDeque;
let mut deque = VecDeque::new();
assert!(deque.is_empty());
deque.push_front(1);
assert!(!deque.is_empty());
1.51.0 · sourcepub fn range<R>(&self, range: R) -> Iter<'_, T>where
R: RangeBounds<usize>,
pub fn range<R>(&self, range: R) -> Iter<'_, T>where
R: RangeBounds<usize>,
Creates an iterator that covers the specified range in the deque.
Panics
Panics if the starting point is greater than the end point or if the end point is greater than the length of the deque.
Examples
use std::collections::VecDeque;
let deque: VecDeque<_> = [1, 2, 3].into();
let range = deque.range(2..).copied().collect::<VecDeque<_>>();
assert_eq!(range, [3]);
// A full range covers all contents
let all = deque.range(..);
assert_eq!(all.len(), 3);
1.51.0 · sourcepub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>where
R: RangeBounds<usize>,
pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>where
R: RangeBounds<usize>,
Creates an iterator that covers the specified mutable range in the deque.
Panics
Panics if the starting point is greater than the end point or if the end point is greater than the length of the deque.
Examples
use std::collections::VecDeque;
let mut deque: VecDeque<_> = [1, 2, 3].into();
for v in deque.range_mut(2..) {
*v *= 2;
}
assert_eq!(deque, [1, 2, 6]);
// A full range covers all contents
for v in deque.range_mut(..) {
*v *= 2;
}
assert_eq!(deque, [2, 4, 12]);
1.6.0 · sourcepub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>where
R: RangeBounds<usize>,
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>where
R: RangeBounds<usize>,
Removes the specified range from the deque in bulk, returning all removed elements as an iterator. If the iterator is dropped before being fully consumed, it drops the remaining removed elements.
The returned iterator keeps a mutable borrow on the queue to optimize its implementation.
Panics
Panics if the starting point is greater than the end point or if the end point is greater than the length of the deque.
Leaking
If the returned iterator goes out of scope without being dropped (due to
mem::forget
, for example), the deque may have lost and leaked
elements arbitrarily, including elements outside the range.
Examples
use std::collections::VecDeque;
let mut deque: VecDeque<_> = [1, 2, 3].into();
let drained = deque.drain(2..).collect::<VecDeque<_>>();
assert_eq!(drained, [3]);
assert_eq!(deque, [1, 2]);
// A full range clears all contents, like `clear()` does
deque.drain(..);
assert!(deque.is_empty());
1.0.0 · sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears the deque, removing all values.
Examples
use std::collections::VecDeque;
let mut deque = VecDeque::new();
deque.push_back(1);
deque.clear();
assert!(deque.is_empty());
1.12.0 · sourcepub fn contains(&self, x: &T) -> boolwhere
T: PartialEq<T>,
pub fn contains(&self, x: &T) -> boolwhere
T: PartialEq<T>,
Returns true
if the deque contains an element equal to the
given value.
This operation is O(n).
Note that if you have a sorted VecDeque
, binary_search
may be faster.
Examples
use std::collections::VecDeque;
let mut deque: VecDeque<u32> = VecDeque::new();
deque.push_back(0);
deque.push_back(1);
assert_eq!(deque.contains(&1), true);
assert_eq!(deque.contains(&10), false);
1.0.0 · sourcepub fn front(&self) -> Option<&T>
pub fn front(&self) -> Option<&T>
Provides a reference to the front element, or None
if the deque is
empty.
Examples
use std::collections::VecDeque;
let mut d = VecDeque::new();
assert_eq!(d.front(), None);
d.push_back(1);
d.push_back(2);
assert_eq!(d.front(), Some(&1));
1.0.0 · sourcepub fn front_mut(&mut self) -> Option<&mut T>
pub fn front_mut(&mut self) -> Option<&mut T>
Provides a mutable reference to the front element, or None
if the
deque is empty.
Examples
use std::collections::VecDeque;
let mut d = VecDeque::new();
assert_eq!(d.front_mut(), None);
d.push_back(1);
d.push_back(2);
match d.front_mut() {
Some(x) => *x = 9,
None => (),
}
assert_eq!(d.front(), Some(&9));
1.0.0 · sourcepub fn back(&self) -> Option<&T>
pub fn back(&self) -> Option<&T>
Provides a reference to the back element, or None
if the deque is
empty.
Examples
use std::collections::VecDeque;
let mut d = VecDeque::new();
assert_eq!(d.back(), None);
d.push_back(1);
d.push_back(2);
assert_eq!(d.back(), Some(&2));
1.0.0 · sourcepub fn back_mut(&mut self) -> Option<&mut T>
pub fn back_mut(&mut self) -> Option<&mut T>
Provides a mutable reference to the back element, or None
if the
deque is empty.
Examples
use std::collections::VecDeque;
let mut d = VecDeque::new();
assert_eq!(d.back(), None);
d.push_back(1);
d.push_back(2);
match d.back_mut() {
Some(x) => *x = 9,
None => (),
}
assert_eq!(d.back(), Some(&9));
1.0.0 · sourcepub fn pop_front(&mut self) -> Option<T>
pub fn pop_front(&mut self) -> Option<T>
Removes the first element and returns it, or None
if the deque is
empty.
Examples
use std::collections::VecDeque;
let mut d = VecDeque::new();
d.push_back(1);
d.push_back(2);
assert_eq!(d.pop_front(), Some(1));
assert_eq!(d.pop_front(), Some(2));
assert_eq!(d.pop_front(), None);
1.0.0 · sourcepub fn pop_back(&mut self) -> Option<T>
pub fn pop_back(&mut self) -> Option<T>
Removes the last element from the deque and returns it, or None
if
it is empty.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
assert_eq!(buf.pop_back(), None);
buf.push_back(1);
buf.push_back(3);
assert_eq!(buf.pop_back(), Some(3));
1.0.0 · sourcepub fn push_front(&mut self, value: T)
pub fn push_front(&mut self, value: T)
Prepends an element to the deque.
Examples
use std::collections::VecDeque;
let mut d = VecDeque::new();
d.push_front(1);
d.push_front(2);
assert_eq!(d.front(), Some(&2));
1.0.0 · sourcepub fn push_back(&mut self, value: T)
pub fn push_back(&mut self, value: T)
Appends an element to the back of the deque.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(1);
buf.push_back(3);
assert_eq!(3, *buf.back().unwrap());
1.5.0 · sourcepub fn swap_remove_front(&mut self, index: usize) -> Option<T>
pub fn swap_remove_front(&mut self, index: usize) -> Option<T>
Removes an element from anywhere in the deque and returns it, replacing it with the first element.
This does not preserve ordering, but is O(1).
Returns None
if index
is out of bounds.
Element at index 0 is the front of the queue.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
assert_eq!(buf.swap_remove_front(0), None);
buf.push_back(1);
buf.push_back(2);
buf.push_back(3);
assert_eq!(buf, [1, 2, 3]);
assert_eq!(buf.swap_remove_front(2), Some(3));
assert_eq!(buf, [2, 1]);
1.5.0 · sourcepub fn swap_remove_back(&mut self, index: usize) -> Option<T>
pub fn swap_remove_back(&mut self, index: usize) -> Option<T>
Removes an element from anywhere in the deque and returns it, replacing it with the last element.
This does not preserve ordering, but is O(1).
Returns None
if index
is out of bounds.
Element at index 0 is the front of the queue.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
assert_eq!(buf.swap_remove_back(0), None);
buf.push_back(1);
buf.push_back(2);
buf.push_back(3);
assert_eq!(buf, [1, 2, 3]);
assert_eq!(buf.swap_remove_back(0), Some(1));
assert_eq!(buf, [3, 2]);
1.5.0 · sourcepub fn insert(&mut self, index: usize, value: T)
pub fn insert(&mut self, index: usize, value: T)
Inserts an element at index
within the deque, shifting all elements
with indices greater than or equal to index
towards the back.
Element at index 0 is the front of the queue.
Panics
Panics if index
is greater than deque’s length
Examples
use std::collections::VecDeque;
let mut vec_deque = VecDeque::new();
vec_deque.push_back('a');
vec_deque.push_back('b');
vec_deque.push_back('c');
assert_eq!(vec_deque, &['a', 'b', 'c']);
vec_deque.insert(1, 'd');
assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1.0.0 · sourcepub fn remove(&mut self, index: usize) -> Option<T>
pub fn remove(&mut self, index: usize) -> Option<T>
Removes and returns the element at index
from the deque.
Whichever end is closer to the removal point will be moved to make
room, and all the affected elements will be moved to new positions.
Returns None
if index
is out of bounds.
Element at index 0 is the front of the queue.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(1);
buf.push_back(2);
buf.push_back(3);
assert_eq!(buf, [1, 2, 3]);
assert_eq!(buf.remove(1), Some(2));
assert_eq!(buf, [1, 3]);
1.4.0 · sourcepub fn split_off(&mut self, at: usize) -> VecDeque<T, A> ⓘwhere
A: Clone,
pub fn split_off(&mut self, at: usize) -> VecDeque<T, A> ⓘwhere
A: Clone,
Splits the deque into two at the given index.
Returns a newly allocated VecDeque
. self
contains elements [0, at)
,
and the returned deque contains elements [at, len)
.
Note that the capacity of self
does not change.
Element at index 0 is the front of the queue.
Panics
Panics if at > len
.
Examples
use std::collections::VecDeque;
let mut buf: VecDeque<_> = [1, 2, 3].into();
let buf2 = buf.split_off(1);
assert_eq!(buf, [1]);
assert_eq!(buf2, [2, 3]);
1.4.0 · sourcepub fn append(&mut self, other: &mut VecDeque<T, A>)
pub fn append(&mut self, other: &mut VecDeque<T, A>)
Moves all the elements of other
into self
, leaving other
empty.
Panics
Panics if the new number of elements in self overflows a usize
.
Examples
use std::collections::VecDeque;
let mut buf: VecDeque<_> = [1, 2].into();
let mut buf2: VecDeque<_> = [3, 4].into();
buf.append(&mut buf2);
assert_eq!(buf, [1, 2, 3, 4]);
assert_eq!(buf2, []);
1.4.0 · sourcepub fn retain<F>(&mut self, f: F)where
F: FnMut(&T) -> bool,
pub fn retain<F>(&mut self, f: F)where
F: FnMut(&T) -> bool,
Retains only the elements specified by the predicate.
In other words, remove all elements e
for which f(&e)
returns false.
This method operates in place, visiting each element exactly once in the
original order, and preserves the order of the retained elements.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.extend(1..5);
buf.retain(|&x| x % 2 == 0);
assert_eq!(buf, [2, 4]);
Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.extend(1..6);
let keep = [false, true, true, false, true];
let mut iter = keep.iter();
buf.retain(|_| *iter.next().unwrap());
assert_eq!(buf, [2, 3, 5]);
1.61.0 · sourcepub fn retain_mut<F>(&mut self, f: F)where
F: FnMut(&mut T) -> bool,
pub fn retain_mut<F>(&mut self, f: F)where
F: FnMut(&mut T) -> bool,
Retains only the elements specified by the predicate.
In other words, remove all elements e
for which f(&e)
returns false.
This method operates in place, visiting each element exactly once in the
original order, and preserves the order of the retained elements.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.extend(1..5);
buf.retain_mut(|x| if *x % 2 == 0 {
*x += 1;
true
} else {
false
});
assert_eq!(buf, [3, 5]);
1.33.0 · sourcepub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T)
pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T)
Modifies the deque in-place so that len()
is equal to new_len
,
either by removing excess elements from the back or by appending
elements generated by calling generator
to the back.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(5);
buf.push_back(10);
buf.push_back(15);
assert_eq!(buf, [5, 10, 15]);
buf.resize_with(5, Default::default);
assert_eq!(buf, [5, 10, 15, 0, 0]);
buf.resize_with(2, || unreachable!());
assert_eq!(buf, [5, 10]);
let mut state = 100;
buf.resize_with(5, || { state += 1; state });
assert_eq!(buf, [5, 10, 101, 102, 103]);
1.48.0 · sourcepub fn make_contiguous(&mut self) -> &mut [T] ⓘ
pub fn make_contiguous(&mut self) -> &mut [T] ⓘ
Rearranges the internal storage of this deque so it is one contiguous slice, which is then returned.
This method does not allocate and does not change the order of the inserted elements. As it returns a mutable slice, this can be used to sort a deque.
Once the internal storage is contiguous, the as_slices
and
as_mut_slices
methods will return the entire contents of the
deque in a single slice.
Examples
Sorting the content of a deque.
use std::collections::VecDeque;
let mut buf = VecDeque::with_capacity(15);
buf.push_back(2);
buf.push_back(1);
buf.push_front(3);
// sorting the deque
buf.make_contiguous().sort();
assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
// sorting it in reverse order
buf.make_contiguous().sort_by(|a, b| b.cmp(a));
assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
Getting immutable access to the contiguous slice.
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(2);
buf.push_back(1);
buf.push_front(3);
buf.make_contiguous();
if let (slice, &[]) = buf.as_slices() {
// we can now be sure that `slice` contains all elements of the deque,
// while still having immutable access to `buf`.
assert_eq!(buf.len(), slice.len());
assert_eq!(slice, &[3, 2, 1] as &[_]);
}
1.36.0 · sourcepub fn rotate_left(&mut self, mid: usize)
pub fn rotate_left(&mut self, mid: usize)
Rotates the double-ended queue mid
places to the left.
Equivalently,
- Rotates item
mid
into the first position. - Pops the first
mid
items and pushes them to the end. - Rotates
len() - mid
places to the right.
Panics
If mid
is greater than len()
. Note that mid == len()
does not panic and is a no-op rotation.
Complexity
Takes *O*(min(mid, len() - mid))
time and no extra space.
Examples
use std::collections::VecDeque;
let mut buf: VecDeque<_> = (0..10).collect();
buf.rotate_left(3);
assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
for i in 1..10 {
assert_eq!(i * 3 % 10, buf[0]);
buf.rotate_left(3);
}
assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1.36.0 · sourcepub fn rotate_right(&mut self, k: usize)
pub fn rotate_right(&mut self, k: usize)
Rotates the double-ended queue k
places to the right.
Equivalently,
- Rotates the first item into position
k
. - Pops the last
k
items and pushes them to the front. - Rotates
len() - k
places to the left.
Panics
If k
is greater than len()
. Note that k == len()
does not panic and is a no-op rotation.
Complexity
Takes *O*(min(k, len() - k))
time and no extra space.
Examples
use std::collections::VecDeque;
let mut buf: VecDeque<_> = (0..10).collect();
buf.rotate_right(3);
assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
for i in 1..10 {
assert_eq!(0, buf[i * 3 % 10]);
buf.rotate_right(3);
}
assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1.54.0 · sourcepub fn binary_search(&self, x: &T) -> Result<usize, usize>where
T: Ord,
pub fn binary_search(&self, x: &T) -> Result<usize, usize>where
T: Ord,
Binary searches this VecDeque
for a given element.
This behaves similarly to contains
if this VecDeque
is sorted.
If the value is found then Result::Ok
is returned, containing the
index of the matching element. If there are multiple matches, then any
one of the matches could be returned. If the value is not found then
Result::Err
is returned, containing the index where a matching
element could be inserted while maintaining sorted order.
See also binary_search_by
, binary_search_by_key
, and partition_point
.
Examples
Looks up a series of four elements. The first is found, with a
uniquely determined position; the second and third are not
found; the fourth could match any position in [1, 4]
.
use std::collections::VecDeque;
let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
assert_eq!(deque.binary_search(&13), Ok(9));
assert_eq!(deque.binary_search(&4), Err(7));
assert_eq!(deque.binary_search(&100), Err(13));
let r = deque.binary_search(&1);
assert!(matches!(r, Ok(1..=4)));
If you want to insert an item to a sorted deque, while maintaining
sort order, consider using partition_point
:
use std::collections::VecDeque;
let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
let num = 42;
let idx = deque.partition_point(|&x| x < num);
// The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);`
deque.insert(idx, num);
assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1.54.0 · sourcepub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>where
F: FnMut(&'a T) -> Ordering,
pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>where
F: FnMut(&'a T) -> Ordering,
Binary searches this VecDeque
with a comparator function.
This behaves similarly to contains
if this VecDeque
is sorted.
The comparator function should implement an order consistent
with the sort order of the deque, returning an order code that
indicates whether its argument is Less
, Equal
or Greater
than the desired target.
If the value is found then Result::Ok
is returned, containing the
index of the matching element. If there are multiple matches, then any
one of the matches could be returned. If the value is not found then
Result::Err
is returned, containing the index where a matching
element could be inserted while maintaining sorted order.
See also binary_search
, binary_search_by_key
, and partition_point
.
Examples
Looks up a series of four elements. The first is found, with a
uniquely determined position; the second and third are not
found; the fourth could match any position in [1, 4]
.
use std::collections::VecDeque;
let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
let r = deque.binary_search_by(|x| x.cmp(&1));
assert!(matches!(r, Ok(1..=4)));
1.54.0 · sourcepub fn binary_search_by_key<'a, B, F>(
&'a self,
b: &B,
f: F
) -> Result<usize, usize>where
F: FnMut(&'a T) -> B,
B: Ord,
pub fn binary_search_by_key<'a, B, F>(
&'a self,
b: &B,
f: F
) -> Result<usize, usize>where
F: FnMut(&'a T) -> B,
B: Ord,
Binary searches this VecDeque
with a key extraction function.
This behaves similarly to contains
if this VecDeque
is sorted.
Assumes that the deque is sorted by the key, for instance with
make_contiguous().sort_by_key()
using the same key extraction function.
If the value is found then Result::Ok
is returned, containing the
index of the matching element. If there are multiple matches, then any
one of the matches could be returned. If the value is not found then
Result::Err
is returned, containing the index where a matching
element could be inserted while maintaining sorted order.
See also binary_search
, binary_search_by
, and partition_point
.
Examples
Looks up a series of four elements in a slice of pairs sorted by
their second elements. The first is found, with a uniquely
determined position; the second and third are not found; the
fourth could match any position in [1, 4]
.
use std::collections::VecDeque;
let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
(3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
(1, 21), (2, 34), (4, 55)].into();
assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
let r = deque.binary_search_by_key(&1, |&(a, b)| b);
assert!(matches!(r, Ok(1..=4)));
1.54.0 · sourcepub fn partition_point<P>(&self, pred: P) -> usizewhere
P: FnMut(&T) -> bool,
pub fn partition_point<P>(&self, pred: P) -> usizewhere
P: FnMut(&T) -> bool,
Returns the index of the partition point according to the given predicate (the index of the first element of the second partition).
The deque is assumed to be partitioned according to the given predicate.
This means that all elements for which the predicate returns true are at the start of the deque
and all elements for which the predicate returns false are at the end.
For example, [7, 15, 3, 5, 4, 12, 6]
is partitioned under the predicate x % 2 != 0
(all odd numbers are at the start, all even at the end).
If the deque is not partitioned, the returned result is unspecified and meaningless, as this method performs a kind of binary search.
See also binary_search
, binary_search_by
, and binary_search_by_key
.
Examples
use std::collections::VecDeque;
let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into();
let i = deque.partition_point(|&x| x < 5);
assert_eq!(i, 4);
assert!(deque.iter().take(i).all(|&x| x < 5));
assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
If you want to insert an item to a sorted deque, while maintaining sort order:
use std::collections::VecDeque;
let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
let num = 42;
let idx = deque.partition_point(|&x| x < num);
deque.insert(idx, num);
assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1.16.0 · sourcepub fn resize(&mut self, new_len: usize, value: T)
pub fn resize(&mut self, new_len: usize, value: T)
Modifies the deque in-place so that len()
is equal to new_len,
either by removing excess elements from the back or by appending clones of value
to the back.
Examples
use std::collections::VecDeque;
let mut buf = VecDeque::new();
buf.push_back(5);
buf.push_back(10);
buf.push_back(15);
assert_eq!(buf, [5, 10, 15]);
buf.resize(2, 0);
assert_eq!(buf, [5, 10]);
buf.resize(5, 20);
assert_eq!(buf, [5, 10, 20, 20, 20]);
Trait Implementations§
source§impl<P, C> Extend<Edge<P, C>> for Wire<P, C>
impl<P, C> Extend<Edge<P, C>> for Wire<P, C>
source§fn extend<T: IntoIterator<Item = Edge<P, C>>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = Edge<P, C>>>(&mut self, iter: T)
source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)source§impl<'a, P, C> FromIterator<&'a Edge<P, C>> for Wire<P, C>
impl<'a, P, C> FromIterator<&'a Edge<P, C>> for Wire<P, C>
source§impl<P, C> FromIterator<Edge<P, C>> for Wire<P, C>
impl<P, C> FromIterator<Edge<P, C>> for Wire<P, C>
source§impl<P: Send, C: Send> FromParallelIterator<Edge<P, C>> for Wire<P, C>
impl<P: Send, C: Send> FromParallelIterator<Edge<P, C>> for Wire<P, C>
source§fn from_par_iter<I>(par_iter: I) -> Selfwhere
I: IntoParallelIterator<Item = Edge<P, C>>,
fn from_par_iter<I>(par_iter: I) -> Selfwhere
I: IntoParallelIterator<Item = Edge<P, C>>,
par_iter
. Read moresource§impl<'a, P, C> IntoIterator for &'a Wire<P, C>
impl<'a, P, C> IntoIterator for &'a Wire<P, C>
source§impl<P, C> IntoIterator for Wire<P, C>
impl<P, C> IntoIterator for Wire<P, C>
source§impl<'a, P: Send + 'a, C: Send + 'a> IntoParallelRefIterator<'a> for Wire<P, C>
impl<'a, P: Send + 'a, C: Send + 'a> IntoParallelRefIterator<'a> for Wire<P, C>
source§impl<'a, P: Send + 'a, C: Send + 'a> IntoParallelRefMutIterator<'a> for Wire<P, C>
impl<'a, P: Send + 'a, C: Send + 'a> IntoParallelRefMutIterator<'a> for Wire<P, C>
§type Item = &'a mut Edge<P, C>
type Item = &'a mut Edge<P, C>
&'data mut T
reference.§type Iter = <VecDeque<Edge<P, C>, Global> as IntoParallelRefMutIterator<'a>>::Iter
type Iter = <VecDeque<Edge<P, C>, Global> as IntoParallelRefMutIterator<'a>>::Iter
source§fn par_iter_mut(&'a mut self) -> Self::Iter
fn par_iter_mut(&'a mut self) -> Self::Iter
self
. Read moresource§impl<P: Send, C: Send> ParallelExtend<Edge<P, C>> for Wire<P, C>
impl<P: Send, C: Send> ParallelExtend<Edge<P, C>> for Wire<P, C>
source§fn par_extend<I>(&mut self, par_iter: I)where
I: IntoParallelIterator<Item = Edge<P, C>>,
fn par_extend<I>(&mut self, par_iter: I)where
I: IntoParallelIterator<Item = Edge<P, C>>,
par_iter
. Read more