logo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
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
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
use derivative::Derivative;
use smallvec::SmallVec;
use std::borrow::Borrow;
use std::hash::{Hash, Hasher};
use std::mem;
use std::ops::{Deref, DerefMut};
use theon::space::Vector;
use theon::AsPosition;

use crate::entity::borrow::{Reborrow, ReborrowInto, ReborrowMut};
use crate::entity::dijkstra;
use crate::entity::storage::prelude::*;
use crate::entity::storage::{
    AsStorage, AsStorageMut, AsStorageOf, HashStorage, IncrementalKeyer, Key,
};
use crate::entity::traverse::{Adjacency, Breadth, Depth, Trace, TraceAny, TraceFirst, Traversal};
use crate::entity::view::{Bind, ClosedView, Orphan, Rebind, Unbind, View};
use crate::entity::{Entity, Payload};
use crate::geometry::Metric;
use crate::graph::data::{Data, GraphData, Parametric};
use crate::graph::edge::{Arc, ArcKey, ArcOrphan, ArcView, Edge};
use crate::graph::face::{Face, FaceKey, FaceOrphan, FaceView};
use crate::graph::geometry::{VertexCentroid, VertexNormal, VertexPosition};
use crate::graph::mutation::vertex::{self, VertexRemoveCache};
use crate::graph::mutation::{self, Consistent, Immediate, Mutable};
use crate::graph::path::Path;
use crate::graph::{GraphError, OptionExt as _, ResultExt as _};
use crate::transact::{BypassOrCommit, Mutate};
use crate::IteratorExt as _;

type Mutation<M> = mutation::Mutation<Immediate<M>>;

/// Vertex entity.
#[derive(Derivative)]
#[derivative(Debug, Hash)]
pub struct Vertex<G>
where
    G: GraphData,
{
    /// User data.
    #[derivative(Debug = "ignore", Hash = "ignore")]
    pub(in crate) data: G::Vertex,
    /// Required key into the leading arc.
    pub(in crate) arc: Option<ArcKey>,
}

impl<G> Vertex<G>
where
    G: GraphData,
{
    pub fn new(data: G::Vertex) -> Self {
        Vertex { data, arc: None }
    }
}

impl<G> Entity for Vertex<G>
where
    G: GraphData,
{
    type Key = VertexKey;
    type Storage = HashStorage<Self, IncrementalKeyer>;
}

impl<G> Payload for Vertex<G>
where
    G: GraphData,
{
    type Data = G::Vertex;

    fn get(&self) -> &Self::Data {
        &self.data
    }

    fn get_mut(&mut self) -> &mut Self::Data {
        &mut self.data
    }
}

/// Vertex key.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct VertexKey(u64);

impl Key for VertexKey {
    type Inner = u64;

    fn from_inner(key: Self::Inner) -> Self {
        VertexKey(key)
    }

    fn into_inner(self) -> Self::Inner {
        self.0
    }
}

/// View of a vertex entity.
///
/// See the [`graph`] module documentation for more information about views.
///
/// [`graph`]: crate::graph
pub struct VertexView<B>
where
    B: Reborrow,
    B::Target: AsStorage<Vertex<Data<B>>> + Parametric,
{
    inner: View<B, Vertex<Data<B>>>,
}

impl<B, M> VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<Data<B>>> + Parametric,
{
    pub fn to_ref(&self) -> VertexView<&M> {
        self.inner.to_ref().into()
    }
}

impl<B, M> VertexView<B>
where
    B: ReborrowMut<Target = M>,
    M: AsStorage<Vertex<Data<B>>> + Parametric,
{
    #[allow(clippy::wrong_self_convention)]
    fn to_mut_unchecked(&mut self) -> VertexView<&mut M> {
        self.inner.to_mut_unchecked().into()
    }
}

impl<'a, B, M, G> VertexView<B>
where
    B: ReborrowInto<'a, Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    // TODO: Relocate this documentation of `into_ref`.
    /// # Examples
    ///
    /// ```rust
    /// # extern crate decorum;
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use decorum::R64;
    /// use nalgebra::Point3;
    /// use plexus::graph::MeshGraph;
    /// use plexus::prelude::*;
    /// use plexus::primitive::cube::Cube;
    /// use plexus::primitive::generate::Position;
    ///
    /// type E3 = Point3<R64>;
    ///
    /// let mut graph: MeshGraph<E3> = Cube::new().polygons::<Position<E3>>().collect();
    /// let key = graph.arcs().nth(0).unwrap().key();
    /// let vertex = graph.arc_mut(key).unwrap().split_at_midpoint().into_ref();
    ///
    /// // This would not be possible without conversion into an immutable view.
    /// let _ = vertex.into_outgoing_arc().into_face().unwrap();
    /// let _ = vertex
    ///     .into_outgoing_arc()
    ///     .into_opposite_arc()
    ///     .into_face()
    ///     .unwrap();
    /// ```
    pub fn into_ref(self) -> VertexView<&'a M> {
        self.inner.into_ref().into()
    }
}

impl<B, M, G> VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    pub fn get<'a>(&'a self) -> &'a G::Vertex
    where
        G: 'a,
    {
        self.inner.get()
    }

    pub fn position<'a>(&'a self) -> &'a VertexPosition<G>
    where
        G: 'a,
        G::Vertex: AsPosition,
    {
        self.data.as_position()
    }
}

impl<B, M, G> VertexView<B>
where
    B: ReborrowMut<Target = M>,
    M: AsStorageMut<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    pub fn get_mut<'a>(&'a mut self) -> &'a mut G::Vertex
    where
        G: 'a,
    {
        self.inner.get_mut()
    }
}

/// Reachable API.
impl<B, M, G> VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    pub(in crate::graph) fn into_reachable_outgoing_arc(self) -> Option<ArcView<B>> {
        let key = self.arc;
        key.and_then(|key| self.rebind(key))
    }
}

impl<B, M, G> VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Consistent + Parametric<Data = G>,
    G: GraphData,
{
    /// Converts the vertex into its outgoing (leading) arc.
    pub fn into_outgoing_arc(self) -> ArcView<B> {
        self.into_reachable_outgoing_arc().expect_consistent()
    }

    /// Gets the outgoing (leading) arc of the vertex.
    pub fn outgoing_arc(&self) -> ArcView<&M> {
        self.to_ref().into_outgoing_arc()
    }

    pub fn shortest_path(&self, key: VertexKey) -> Result<Path<'static, &M>, GraphError> {
        self.to_ref().into_shortest_path(key)
    }

    pub fn into_shortest_path(self, key: VertexKey) -> Result<Path<'static, B>, GraphError> {
        self.into_shortest_path_with(key, |_, _| 1usize)
    }

    pub fn shortest_path_with<Q, F>(
        &self,
        key: VertexKey,
        f: F,
    ) -> Result<Path<'static, &M>, GraphError>
    where
        Q: Copy + Metric,
        F: Fn(VertexView<&M>, VertexView<&M>) -> Q,
    {
        self.to_ref().into_shortest_path_with(key, f)
    }

    pub fn into_shortest_path_with<Q, F>(
        self,
        mut key: VertexKey,
        f: F,
    ) -> Result<Path<'static, B>, GraphError>
    where
        Q: Copy + Metric,
        F: Fn(VertexView<&M>, VertexView<&M>) -> Q,
    {
        let metrics = dijkstra::metrics_with(self.to_ref(), Some(key), f)?;
        let mut keys = vec![key];
        while let Some((Some(previous), _)) = metrics.get(&key) {
            key = *previous;
            keys.push(key);
        }
        if keys.len() < 2 {
            return Err(GraphError::TopologyUnreachable);
        }
        let (storage, _) = self.unbind();
        Path::bind(storage, keys.iter().rev())
    }

    /// Gets the valence of the vertex.
    ///
    /// A vertex's _valence_ is the number of adjacent vertices to which it is
    /// connected by arcs. The valence of a vertex is the same as its _degree_,
    /// which is the number of edges to which the vertex is connected.
    pub fn valence(&self) -> usize {
        self.adjacent_vertices().count()
    }

    pub fn centroid(&self) -> VertexPosition<G>
    where
        G: VertexCentroid,
        G::Vertex: AsPosition,
    {
        <G as VertexCentroid>::centroid(self.to_ref()).expect_consistent()
    }
}

impl<B, M, G> VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Arc<G>>
        + AsStorage<Face<G>>
        + AsStorage<Vertex<G>>
        + Consistent
        + Parametric<Data = G>,
    G: GraphData,
{
    pub fn normal(&self) -> Result<Vector<VertexPosition<G>>, GraphError>
    where
        G: VertexNormal,
        G::Vertex: AsPosition,
    {
        <G as VertexNormal>::normal(self.to_ref())
    }
}

/// Reachable API.
impl<'a, B, M, G> VertexView<B>
where
    B: ReborrowInto<'a, Target = M>,
    M: 'a + AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    pub(in crate::graph) fn into_reachable_incoming_arcs(
        self,
    ) -> impl Clone + Iterator<Item = ArcView<&'a M>> {
        // This reachable circulator is needed for face insertions.
        ArcCirculator::<TraceAny<_>, _>::from(self.into_ref())
    }

    pub(in crate::graph) fn into_reachable_outgoing_arcs(
        self,
    ) -> impl Clone + Iterator<Item = ArcView<&'a M>> {
        // This reachable circulator is needed for face insertions.
        self.into_reachable_incoming_arcs()
            .flat_map(|arc| arc.into_reachable_opposite_arc())
    }
}

/// Reachable API.
impl<B, G> VertexView<B>
where
    B: Reborrow,
    B::Target: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    pub(in crate::graph) fn reachable_incoming_arcs(
        &self,
    ) -> impl Clone + Iterator<Item = ArcView<&B::Target>> {
        self.to_ref().into_reachable_incoming_arcs()
    }

    pub(in crate::graph) fn reachable_outgoing_arcs(
        &self,
    ) -> impl Clone + Iterator<Item = ArcView<&B::Target>> {
        self.to_ref().into_reachable_outgoing_arcs()
    }
}

impl<'a, B, M, G> VertexView<B>
where
    B: ReborrowInto<'a, Target = M>,
    M: 'a + AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Consistent + Parametric<Data = G>,
    G: GraphData,
{
    pub fn into_adjacent_vertices(self) -> impl Clone + Iterator<Item = VertexView<&'a M>> {
        VertexCirculator::from(ArcCirculator::<TraceFirst<_>, _>::from(self.into_ref()))
    }

    pub fn into_incoming_arcs(self) -> impl Clone + Iterator<Item = ArcView<&'a M>> {
        ArcCirculator::<TraceFirst<_>, _>::from(self.into_ref())
    }

    pub fn into_outgoing_arcs(self) -> impl Clone + Iterator<Item = ArcView<&'a M>> {
        self.into_incoming_arcs().map(|arc| arc.into_opposite_arc())
    }
}

impl<B, G> VertexView<B>
where
    B: Reborrow,
    B::Target: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Consistent + Parametric<Data = G>,
    G: GraphData,
{
    pub fn adjacent_vertices(&self) -> impl Clone + Iterator<Item = VertexView<&B::Target>> {
        self.to_ref().into_adjacent_vertices()
    }

    /// Gets an iterator of views over the incoming arcs of the vertex.
    ///
    /// The ordering of arcs is deterministic and is based on the leading arc of
    /// the vertex.
    pub fn incoming_arcs(&self) -> impl Clone + Iterator<Item = ArcView<&B::Target>> {
        self.to_ref().into_incoming_arcs()
    }

    /// Gets an iterator of views over the outgoing arcs of the vertex.
    ///
    /// The ordering of arcs is deterministic and is based on the leading arc of
    /// the vertex.
    pub fn outgoing_arcs(&self) -> impl Clone + Iterator<Item = ArcView<&B::Target>> {
        self.to_ref().into_outgoing_arcs()
    }

    /// Gets an iterator that traverses adjacent vertices by breadth.
    ///
    /// The traversal moves from the vertex to its adjacent vertices and so on.
    /// If there are disjoint subgraphs in the graph, then a traversal will not
    /// reach every vertex in the graph.
    pub fn traverse_by_breadth(&self) -> impl Clone + Iterator<Item = VertexView<&B::Target>> {
        Traversal::<_, _, Breadth>::from(self.to_ref())
    }

    /// Gets an iterator that traverses adjacent vertices by depth.
    ///
    /// The traversal moves from the vertex to its adjacent vertices and so on.
    /// If there are disjoint subgraphs in the graph, then a traversal will not
    /// reach every vertex in the graph.
    pub fn traverse_by_depth(&self) -> impl Clone + Iterator<Item = VertexView<&B::Target>> {
        Traversal::<_, _, Depth>::from(self.to_ref())
    }
}

impl<'a, B, M, G> VertexView<B>
where
    B: ReborrowInto<'a, Target = M>,
    M: 'a
        + AsStorage<Arc<G>>
        + AsStorage<Face<G>>
        + AsStorage<Vertex<G>>
        + Consistent
        + Parametric<Data = G>,
    G: GraphData,
{
    pub fn into_adjacent_faces(self) -> impl Clone + Iterator<Item = FaceView<&'a M>> {
        FaceCirculator::from(ArcCirculator::<TraceFirst<_>, _>::from(self.into_ref()))
    }
}

impl<B, G> VertexView<B>
where
    B: Reborrow,
    B::Target: AsStorage<Arc<G>>
        + AsStorage<Face<G>>
        + AsStorage<Vertex<G>>
        + Consistent
        + Parametric<Data = G>,
    G: GraphData,
{
    /// Gets an iterator of views over the adjacent faces of the vertex.
    ///
    /// The ordering of faces is deterministic and is based on the leading arc
    /// of the vertex.
    pub fn adjacent_faces(&self) -> impl Clone + Iterator<Item = FaceView<&B::Target>> {
        self.to_ref().into_adjacent_faces()
    }
}

impl<'a, M, G> VertexView<&'a mut M>
where
    M: AsStorage<Arc<G>> + AsStorageMut<Vertex<G>> + Consistent + Parametric<Data = G>,
    G: 'a + GraphData,
{
    pub fn into_adjacent_vertex_orphans(self) -> impl Iterator<Item = VertexOrphan<'a, G>> {
        VertexCirculator::from(ArcCirculator::<TraceFirst<_>, _>::from(self))
    }
}

impl<B> VertexView<B>
where
    B: ReborrowMut,
    B::Target: AsStorage<Arc<Data<B>>> + AsStorageMut<Vertex<Data<B>>> + Consistent + Parametric,
{
    pub fn adjacent_vertex_orphans(&mut self) -> impl Iterator<Item = VertexOrphan<Data<B>>> {
        self.to_mut_unchecked().into_adjacent_vertex_orphans()
    }
}

impl<'a, M, G> VertexView<&'a mut M>
where
    M: AsStorageMut<Arc<G>> + AsStorage<Vertex<G>> + Consistent + Parametric<Data = G>,
    G: 'a + GraphData,
{
    pub fn into_incoming_arc_orphans(self) -> impl Iterator<Item = ArcOrphan<'a, G>> {
        ArcCirculator::<TraceFirst<_>, _>::from(self)
    }
}

impl<B> VertexView<B>
where
    B: ReborrowMut,
    B::Target: AsStorageMut<Arc<Data<B>>> + AsStorage<Vertex<Data<B>>> + Consistent + Parametric,
{
    /// Gets an iterator of orphan views over the incoming arcs of the vertex.
    ///
    /// The ordering of arcs is deterministic and is based on the leading arc of
    /// the vertex.
    pub fn incoming_arc_orphans(&mut self) -> impl Iterator<Item = ArcOrphan<Data<B>>> {
        self.to_mut_unchecked().into_incoming_arc_orphans()
    }
}

impl<'a, M, G> VertexView<&'a mut M>
where
    M: AsStorage<Arc<G>>
        + AsStorageMut<Face<G>>
        + AsStorage<Vertex<G>>
        + Consistent
        + Parametric<Data = G>,
    G: 'a + GraphData,
{
    pub fn into_adjacent_face_orphans(self) -> impl Iterator<Item = FaceOrphan<'a, G>> {
        FaceCirculator::from(ArcCirculator::<TraceFirst<_>, _>::from(self))
    }
}

impl<B> VertexView<B>
where
    B: ReborrowMut,
    B::Target: AsStorage<Arc<Data<B>>>
        + AsStorageMut<Face<Data<B>>>
        + AsStorage<Vertex<Data<B>>>
        + Consistent
        + Parametric,
{
    /// Gets an iterator of orphan views over the adjacent faces of the vertex.
    ///
    /// The ordering of faces is deterministic and is based on the leading arc
    /// of the vertex.
    pub fn adjacent_face_orphans(&mut self) -> impl Iterator<Item = FaceOrphan<Data<B>>> {
        self.to_mut_unchecked().into_adjacent_face_orphans()
    }
}

impl<'a, M, G> VertexView<&'a mut M>
where
    M: AsStorage<Arc<G>>
        + AsStorage<Edge<G>>
        + AsStorage<Face<G>>
        + AsStorage<Vertex<G>>
        + Default
        + Mutable<Data = G>,
    G: GraphData,
{
    // TODO: This is not yet implemented, so examples use `no_run`. Run these
    //       examples in doc tests once this no longer intentionally panics.
    /// Removes the vertex.
    ///
    /// Any and all dependent entities are also removed, such as arcs and edges
    /// connected to the vertex, faces connected to such arcs, vertices with no
    /// remaining leading arc, etc.
    ///
    /// Vertex removal is the most destructive removal, because vertices are a
    /// dependency of all other entities.
    ///
    /// # Examples
    ///
    /// Removing a corner from a cube by removing its vertex:
    ///
    /// ```rust,no_run
    /// # extern crate decorum;
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use decorum::R64;
    /// use nalgebra::Point3;
    /// use plexus::graph::MeshGraph;
    /// use plexus::prelude::*;
    /// use plexus::primitive::cube::Cube;
    /// use plexus::primitive::generate::Position;
    ///
    /// type E3 = Point3<R64>;
    ///
    /// let mut graph: MeshGraph<E3> = Cube::new().polygons::<Position<E3>>().collect();
    /// let key = graph.vertices().nth(0).unwrap().key();
    /// graph.vertex_mut(key).unwrap().remove();
    /// ```
    pub fn remove(self) {
        // This should never fail here.
        let cache = VertexRemoveCache::from_vertex(self.to_ref()).expect_consistent();
        let (storage, _) = self.unbind();
        Mutation::take(storage)
            .bypass_or_commit_with(|mutation| vertex::remove(mutation, cache))
            .map(|_| ())
            .map_err(|(_, error)| error)
            .expect_consistent()
    }
}

impl<B, M, G> Adjacency for VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Consistent + Parametric<Data = G>,
    G: GraphData,
{
    type Output = SmallVec<[Self::Key; 8]>;

    fn adjacency(&self) -> Self::Output {
        self.adjacent_vertices().keys().collect()
    }
}

impl<B> Borrow<VertexKey> for VertexView<B>
where
    B: Reborrow,
    B::Target: AsStorage<Vertex<Data<B>>> + Parametric,
{
    fn borrow(&self) -> &VertexKey {
        self.inner.as_ref()
    }
}

impl<B, M, G> Clone for VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
    View<B, Vertex<G>>: Clone,
{
    fn clone(&self) -> Self {
        VertexView {
            inner: self.inner.clone(),
        }
    }
}

impl<B, M, G> ClosedView for VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    type Key = VertexKey;
    type Entity = Vertex<G>;

    fn key(&self) -> Self::Key {
        self.inner.key()
    }
}

impl<B, M, G> Copy for VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
    View<B, Vertex<G>>: Copy,
{
}

impl<B, M, G> Deref for VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    type Target = Vertex<G>;

    fn deref(&self) -> &Self::Target {
        self.inner.deref()
    }
}

impl<B, M, G> DerefMut for VertexView<B>
where
    B: ReborrowMut<Target = M>,
    M: AsStorageMut<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.deref_mut()
    }
}

impl<B, M, G> Eq for VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
}

impl<B, M, G> From<View<B, Vertex<G>>> for VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn from(view: View<B, Vertex<G>>) -> Self {
        VertexView { inner: view }
    }
}

impl<B, M, G> From<VertexView<B>> for View<B, Vertex<G>>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn from(vertex: VertexView<B>) -> Self {
        let VertexView { inner, .. } = vertex;
        inner
    }
}

impl<B, M, G> Hash for VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.inner.hash(state);
    }
}

impl<B, M, G> PartialEq for VertexView<B>
where
    B: Reborrow<Target = M>,
    M: AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

/// Orphan view of a vertex entity.
pub struct VertexOrphan<'a, G>
where
    G: GraphData,
{
    inner: Orphan<'a, Vertex<G>>,
}

impl<'a, G> VertexOrphan<'a, G>
where
    G: GraphData,
{
    pub fn position(&self) -> &VertexPosition<G>
    where
        G::Vertex: AsPosition,
    {
        self.inner.get().as_position()
    }
}

impl<'a, G> VertexOrphan<'a, G>
where
    G: 'a + GraphData,
{
    pub fn get(&self) -> &G::Vertex {
        self.inner.get()
    }

    pub fn get_mut(&mut self) -> &mut G::Vertex {
        self.inner.get_mut()
    }
}

impl<'a, G> Borrow<VertexKey> for VertexOrphan<'a, G>
where
    G: GraphData,
{
    fn borrow(&self) -> &VertexKey {
        self.inner.as_ref()
    }
}

impl<'a, G> ClosedView for VertexOrphan<'a, G>
where
    G: GraphData,
{
    type Key = VertexKey;
    type Entity = Vertex<G>;

    fn key(&self) -> Self::Key {
        self.inner.key()
    }
}

impl<'a, G> Eq for VertexOrphan<'a, G> where G: GraphData {}

impl<'a, G> From<Orphan<'a, Vertex<G>>> for VertexOrphan<'a, G>
where
    G: GraphData,
{
    fn from(inner: Orphan<'a, Vertex<G>>) -> Self {
        VertexOrphan { inner }
    }
}

impl<'a, M, G> From<View<&'a mut M, Vertex<G>>> for VertexOrphan<'a, G>
where
    M: AsStorageMut<Vertex<G>> + Parametric<Data = G>,
    G: 'a + GraphData,
{
    fn from(view: View<&'a mut M, Vertex<G>>) -> Self {
        VertexOrphan { inner: view.into() }
    }
}

impl<'a, M, G> From<VertexView<&'a mut M>> for VertexOrphan<'a, G>
where
    M: AsStorageMut<Vertex<G>> + Parametric<Data = G>,
    G: 'a + GraphData,
{
    fn from(vertex: VertexView<&'a mut M>) -> Self {
        Orphan::from(vertex.inner).into()
    }
}

impl<'a, G> Hash for VertexOrphan<'a, G>
where
    G: GraphData,
{
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.inner.hash(state);
    }
}

impl<'a, G> PartialEq for VertexOrphan<'a, G>
where
    G: GraphData,
{
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

pub struct VertexCirculator<P, B>
where
    P: Trace<ArcKey>,
    B: Reborrow,
    B::Target: AsStorage<Arc<Data<B>>> + AsStorage<Vertex<Data<B>>> + Parametric,
{
    inner: ArcCirculator<P, B>,
}

impl<P, B, M, G> VertexCirculator<P, B>
where
    P: Trace<ArcKey>,
    B: Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn next(&mut self) -> Option<VertexKey> {
        self.inner.next().map(|arc| {
            let (source, _) = arc.into();
            source
        })
    }
}

impl<P, B, M, G> Clone for VertexCirculator<P, B>
where
    P: Clone + Trace<ArcKey>,
    B: Clone + Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn clone(&self) -> Self {
        VertexCirculator {
            inner: self.inner.clone(),
        }
    }
}

impl<P, B, M, G> From<ArcCirculator<P, B>> for VertexCirculator<P, B>
where
    P: Trace<ArcKey>,
    B: Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn from(inner: ArcCirculator<P, B>) -> Self {
        VertexCirculator { inner }
    }
}

impl<'a, P, M, G> Iterator for VertexCirculator<P, &'a M>
where
    P: Trace<ArcKey>,
    M: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    type Item = VertexView<&'a M>;

    fn next(&mut self) -> Option<Self::Item> {
        VertexCirculator::next(self).and_then(|key| Bind::bind(self.inner.storage, key))
    }
}

impl<'a, P, M, G> Iterator for VertexCirculator<P, &'a mut M>
where
    P: Trace<ArcKey>,
    M: AsStorage<Arc<G>> + AsStorageMut<Vertex<G>> + Parametric<Data = G>,
    G: 'a + GraphData,
{
    type Item = VertexOrphan<'a, G>;

    fn next(&mut self) -> Option<Self::Item> {
        VertexCirculator::next(self).map(|key| {
            let vertex = self.inner.storage.as_storage_mut().get_mut(&key).unwrap();
            let data = &mut vertex.data;
            let data = unsafe { mem::transmute::<&'_ mut G::Vertex, &'a mut G::Vertex>(data) };
            Orphan::bind_unchecked(data, key).into()
        })
    }
}

pub struct ArcCirculator<P, B>
where
    P: Trace<ArcKey>,
    B: Reborrow,
    B::Target: AsStorage<Arc<Data<B>>> + Parametric,
{
    storage: B,
    outgoing: Option<ArcKey>,
    trace: P,
}

impl<P, B, M, G> ArcCirculator<P, B>
where
    P: Trace<ArcKey>,
    B: Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn next(&mut self) -> Option<ArcKey> {
        self.outgoing
            .and_then(|outgoing| self.trace.insert(outgoing).then(|| outgoing))
            .map(|outgoing| outgoing.into_opposite())
            .and_then(|incoming| {
                self.storage
                    .reborrow()
                    .as_storage()
                    .get(&incoming)
                    .map(|incoming| incoming.next)
                    .map(|outgoing| (incoming, outgoing))
            })
            .map(|(incoming, outgoing)| {
                self.outgoing = outgoing;
                incoming
            })
    }
}

impl<P, B, M, G> Clone for ArcCirculator<P, B>
where
    P: Clone + Trace<ArcKey>,
    B: Clone + Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn clone(&self) -> Self {
        ArcCirculator {
            storage: self.storage.clone(),
            outgoing: self.outgoing,
            trace: self.trace.clone(),
        }
    }
}

impl<P, B, M, G> From<VertexView<B>> for ArcCirculator<P, B>
where
    P: Default + Trace<ArcKey>,
    B: Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn from(vertex: VertexView<B>) -> Self {
        let key = vertex.arc;
        let (storage, _) = vertex.unbind();
        ArcCirculator {
            storage,
            outgoing: key,
            trace: Default::default(),
        }
    }
}

impl<'a, P, M, G> Iterator for ArcCirculator<P, &'a M>
where
    P: Trace<ArcKey>,
    M: AsStorage<Arc<G>> + Parametric<Data = G>,
    G: GraphData,
{
    type Item = ArcView<&'a M>;

    fn next(&mut self) -> Option<Self::Item> {
        ArcCirculator::next(self).and_then(|key| Bind::bind(self.storage, key))
    }
}

impl<'a, P, M, G> Iterator for ArcCirculator<P, &'a mut M>
where
    P: Trace<ArcKey>,
    M: AsStorageMut<Arc<G>> + Parametric<Data = G>,
    G: 'a + GraphData,
{
    type Item = ArcOrphan<'a, G>;

    fn next(&mut self) -> Option<Self::Item> {
        ArcCirculator::next(self).map(|key| {
            let arc = self.storage.as_storage_mut().get_mut(&key).unwrap();
            let data = &mut arc.data;
            let data = unsafe { mem::transmute::<&'_ mut G::Arc, &'a mut G::Arc>(data) };
            Orphan::bind_unchecked(data, key).into()
        })
    }
}

pub struct FaceCirculator<P, B>
where
    P: Trace<ArcKey>,
    B: Reborrow,
    B::Target: AsStorage<Arc<Data<B>>> + AsStorage<Face<Data<B>>> + Parametric,
{
    inner: ArcCirculator<P, B>,
}

impl<P, B, M, G> FaceCirculator<P, B>
where
    P: Trace<ArcKey>,
    B: Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + AsStorage<Face<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn next(&mut self) -> Option<FaceKey> {
        while let Some(arc) = self.inner.next() {
            if let Some(face) = self
                .inner
                .storage
                .reborrow()
                .as_storage_of::<Arc<_>>()
                .get(&arc)
                .and_then(|arc| arc.face)
            {
                return Some(face);
            }
            else {
                // Skip arcs with no face. This can occur within non-enclosed
                // meshes.
                continue;
            }
        }
        None
    }
}

impl<P, B, M, G> Clone for FaceCirculator<P, B>
where
    P: Clone + Trace<ArcKey>,
    B: Clone + Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + AsStorage<Face<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn clone(&self) -> Self {
        FaceCirculator {
            inner: self.inner.clone(),
        }
    }
}

impl<P, B, M, G> From<ArcCirculator<P, B>> for FaceCirculator<P, B>
where
    P: Trace<ArcKey>,
    B: Reborrow<Target = M>,
    M: AsStorage<Arc<G>> + AsStorage<Face<G>> + Parametric<Data = G>,
    G: GraphData,
{
    fn from(inner: ArcCirculator<P, B>) -> Self {
        FaceCirculator { inner }
    }
}

impl<'a, P, M, G> Iterator for FaceCirculator<P, &'a M>
where
    P: Trace<ArcKey>,
    M: AsStorage<Arc<G>> + AsStorage<Face<G>> + Parametric<Data = G>,
    G: GraphData,
{
    type Item = FaceView<&'a M>;

    fn next(&mut self) -> Option<Self::Item> {
        FaceCirculator::next(self).and_then(|key| Bind::bind(self.inner.storage, key))
    }
}

impl<'a, P, M, G> Iterator for FaceCirculator<P, &'a mut M>
where
    P: Trace<ArcKey>,
    M: AsStorage<Arc<G>> + AsStorageMut<Face<G>> + Parametric<Data = G>,
    G: 'a + GraphData,
{
    type Item = FaceOrphan<'a, G>;

    fn next(&mut self) -> Option<Self::Item> {
        FaceCirculator::next(self).map(|key| {
            let face = self.inner.storage.as_storage_mut().get_mut(&key).unwrap();
            let data = &mut face.data;
            let data = unsafe { mem::transmute::<&'_ mut G::Face, &'a mut G::Face>(data) };
            Orphan::bind_unchecked(data, key).into()
        })
    }
}

#[cfg(test)]
mod tests {
    use decorum::R64;
    use nalgebra::{Point2, Point3};

    use crate::graph::{GraphError, MeshGraph};
    use crate::prelude::*;
    use crate::primitive::cube::Cube;
    use crate::primitive::generate::Position;
    use crate::primitive::sphere::UvSphere;
    use crate::primitive::Trigon;

    type E3 = Point3<R64>;

    #[test]
    fn circulate_over_arcs() {
        let graph: MeshGraph<E3> = UvSphere::new(4, 2)
            .polygons::<Position<E3>>() // 6 triangles, 18 vertices.
            .collect();

        // All faces should be triangles and all vertices should have 4
        // (incoming) arcs.
        for vertex in graph.vertices() {
            assert_eq!(4, vertex.incoming_arcs().count());
        }
    }

    #[test]
    fn reachable_shortest_path() {
        let graph = MeshGraph::<Point2<f64>>::from_raw_buffers(
            vec![Trigon::new(0usize, 1, 2)],
            vec![(-1.0, 0.0), (0.0, 1.0), (1.0, 0.0)],
        )
        .unwrap();
        let from = graph.vertices().nth(0).unwrap();
        let to = from.outgoing_arc().destination_vertex().key();
        let path = from.shortest_path(to).unwrap();

        assert_eq!(path.back().key(), from.key());
        assert_eq!(path.front().key(), to);
        assert_eq!(path.arcs().count(), 1);
    }

    #[test]
    fn unreachable_shortest_path() {
        // Create a graph from two disjoint trigons.
        let graph = MeshGraph::<Point2<f64>>::from_raw_buffers(
            vec![Trigon::new(0usize, 1, 2), Trigon::new(3, 4, 5)],
            vec![
                (-2.0, 0.0),
                (-1.0, 1.0),
                (-1.0, 0.0),
                (0.0, 0.0),
                (1.0, 1.0),
                (1.0, 0.0),
            ],
        )
        .unwrap();
        let mut vertices = graph.disjoint_subgraph_vertices();
        let from = vertices.next().unwrap();
        let to = vertices.next().unwrap().key();

        assert!(matches!(
            from.into_shortest_path(to),
            Err(GraphError::TopologyUnreachable)
        ));
    }

    #[test]
    fn traverse_by_breadth() {
        let graph: MeshGraph<E3> = Cube::new()
            .polygons::<Position<E3>>() // 6 quadrilaterals, 24 vertices.
            .collect();

        let vertex = graph.vertices().nth(0).unwrap();
        assert_eq!(graph.vertex_count(), vertex.traverse_by_breadth().count());
    }

    #[test]
    fn traverse_by_depth() {
        let graph: MeshGraph<E3> = Cube::new()
            .polygons::<Position<E3>>() // 6 quadrilaterals, 24 vertices.
            .collect();

        let vertex = graph.vertices().nth(0).unwrap();
        assert_eq!(graph.vertex_count(), vertex.traverse_by_depth().count());
    }
}