forked from Qiskit/rustworkx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterators.rs
1880 lines (1598 loc) · 54.7 KB
/
iterators.rs
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
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
// There are two useful macros to quickly define a new custom return type:
//
// :`custom_vec_iter_impl` holds a `Vec<T>` and can be used as a
// read-only sequence/list. To use it, you should specify the name of the new type for the
// iterable, a name for that new type's iterator, a name for the new type's reversed iterator, the
// name of the vector that holds the data, the type `T` and a docstring.
//
// e.g `custom_vec_iter_impl!(MyReadOnlyType, data, (usize, f64), "Docs");`
// defines a new type named `MyReadOnlyType` that holds a vector called `data`
// of values `(usize, f64)`.
//
// :`custom_hash_map_iter_impl` holds a `DictMap<K, V>` and can be used as
// a read-only mapping/dict. To use it, you should specify the name of the new type,
// the name of the hash map that holds the data, the type of the keys `K`,
// the type of the values `V` and a docstring.
//
// e.g `custom_hash_map_iter_impl!(MyReadOnlyType, data, usize, f64, "Docs");`
// defines a new type named `MyReadOnlyType` that holds a mapping called `data`
// from `usize` to `f64`.
//
// You should always implement `PyGCProtocol` for the new custom return type. If you
// don't store any python object, just use `impl PyGCProtocol for MyReadOnlyType {}`.
//
// Types `T, K, V` above should implement `PyHash`, `PyEq`, `PyDisplay` traits.
// These are arleady implemented for many primitive rust types and `PyObject`.
#![allow(clippy::float_cmp, clippy::upper_case_acronyms)]
use std::collections::hash_map::DefaultHasher;
use std::convert::TryInto;
use std::hash::Hasher;
use num_bigint::BigUint;
use rustworkx_core::dictmap::*;
use ndarray::prelude::*;
use numpy::{IntoPyArray, PyArrayDescr};
use pyo3::class::iter::IterNextOutput;
use pyo3::exceptions::{PyIndexError, PyKeyError, PyNotImplementedError};
use pyo3::gc::PyVisit;
use pyo3::prelude::*;
use pyo3::types::PySlice;
use pyo3::PyTraverseError;
macro_rules! last_type {
($a:ident,) => { $a };
($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
}
// similar to `std::hash::Hash` trait.
trait PyHash {
fn hash<H: Hasher>(&self, py: Python, state: &mut H) -> PyResult<()>;
}
impl PyHash for PyObject {
#[inline]
fn hash<H: Hasher>(&self, py: Python, state: &mut H) -> PyResult<()> {
state.write_isize(self.as_ref(py).hash()?);
Ok(())
}
}
// see https://doc.rust-lang.org/src/core/hash/mod.rs.html#553
macro_rules! pyhash_impl {
($(($ty:ident, $meth:ident),)*) => ($(
impl PyHash for $ty {
#[inline]
fn hash<H: Hasher>(&self, _: Python, state: &mut H) -> PyResult<()>{
state.$meth(*self);
Ok(())
}
}
)*)
}
pyhash_impl! {
(u8, write_u8),
(u16, write_u16),
(u32, write_u32),
(u64, write_u64),
(usize, write_usize),
(i8, write_i8),
(i16, write_i16),
(i32, write_i32),
(i64, write_i64),
(isize, write_isize),
(u128, write_u128),
(i128, write_i128),
}
impl PyHash for f64 {
#[inline]
fn hash<H: Hasher>(&self, _: Python, state: &mut H) -> PyResult<()> {
state.write(&self.to_be_bytes());
Ok(())
}
}
impl PyHash for BigUint {
#[inline]
fn hash<H: Hasher>(&self, _: Python, state: &mut H) -> PyResult<()> {
self.iter_u64_digits().for_each(|i| state.write_u64(i));
Ok(())
}
}
// see https://doc.rust-lang.org/src/core/hash/mod.rs.html#624
macro_rules! pyhash_tuple_impls {
( $($name:ident)+) => (
impl<$($name: PyHash),+> PyHash for ($($name,)+) where last_type!($($name,)+): ?Sized {
#[allow(non_snake_case)]
#[inline]
fn hash<S: Hasher>(&self, py: Python, state: &mut S) -> PyResult<()> {
let ($(ref $name,)+) = *self;
$($name.hash(py, state)?;)+
Ok(())
}
}
);
}
pyhash_tuple_impls! { A }
pyhash_tuple_impls! { A B }
pyhash_tuple_impls! { A B C }
impl<T: PyHash> PyHash for [T] {
#[inline]
fn hash<H: Hasher>(&self, py: Python, state: &mut H) -> PyResult<()> {
// self.len().hash(py, state)?;
for elem in self {
elem.hash(py, state)?;
}
Ok(())
}
}
macro_rules! pyhash_array_impls {
($($N:expr)+) => {$(
impl<T: PyHash> PyHash for [T; $N] {
fn hash<H: Hasher>(&self, py: Python, state: &mut H) -> PyResult<()> {
PyHash::hash(&self[..], py, state)?;
Ok(())
}
}
)+}
}
pyhash_array_impls! {2 3}
impl<T: PyHash> PyHash for Vec<T> {
#[inline]
fn hash<H: Hasher>(&self, py: Python, state: &mut H) -> PyResult<()> {
PyHash::hash(&self[..], py, state)?;
Ok(())
}
}
impl<K: PyHash, V: PyHash> PyHash for DictMap<K, V> {
#[inline]
fn hash<H: Hasher>(&self, py: Python, state: &mut H) -> PyResult<()> {
for (key, value) in self {
key.hash(py, state)?;
value.hash(py, state)?;
}
Ok(())
}
}
// similar to `std::cmp::PartialEq` trait.
trait PyEq<Rhs: ?Sized = Self> {
fn eq(&self, other: &Rhs, py: Python) -> PyResult<bool>;
}
impl PyEq for PyObject {
#[inline]
fn eq(&self, other: &Self, py: Python) -> PyResult<bool> {
Ok(self.as_ref(py).compare(other)? == std::cmp::Ordering::Equal)
}
}
macro_rules! pyeq_impl {
($($t:ty)*) => ($(
impl PyEq for $t {
#[inline]
fn eq(&self, other: &Self, _: Python) -> PyResult<bool> {
Ok((*self) == (*other))
}
}
)*)
}
pyeq_impl! {bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 BigUint}
// see https://doc.rust-lang.org/src/core/tuple.rs.html#7
macro_rules! pyeq_tuple_impls {
($(
$Tuple:ident {
$(($idx:tt) -> $T:ident)+
}
)+) => {
$(
impl<$($T:PyEq),+> PyEq for ($($T,)+) where last_type!($($T,)+): ?Sized {
#[allow(clippy::needless_question_mark)]
#[inline]
fn eq(&self, other: &($($T,)+), py: Python) -> PyResult<bool> {
Ok($(self.$idx.eq(&other.$idx, py)?)&&+)
}
}
)+
}
}
pyeq_tuple_impls! {
Tuple1 {
(0) -> A
}
Tuple2 {
(0) -> A
(1) -> B
}
Tuple3 {
(0) -> A
(1) -> B
(2) -> C
}
}
impl<A, B> PyEq<[B]> for [A]
where
A: PyEq<B>,
{
#[inline]
fn eq(&self, other: &[B], py: Python) -> PyResult<bool> {
if self.len() != other.len() {
return Ok(false);
}
for (x, y) in self.iter().zip(other.iter()) {
if !PyEq::eq(x, y, py)? {
return Ok(false);
}
}
Ok(true)
}
}
macro_rules! pyeq_array_impls {
($($N:expr)+) => {$(
impl<A, B> PyEq<[B; $N]> for [A; $N]
where
A: PyEq<B>,
{
#[inline]
fn eq(&self, other: &[B; $N], py: Python) -> PyResult<bool> {
PyEq::eq(&self[..], &other[..], py)
}
}
)+}
}
pyeq_array_impls! {2 3}
impl<A, B> PyEq<Vec<B>> for Vec<A>
where
A: PyEq<B>,
{
#[inline]
fn eq(&self, other: &Vec<B>, py: Python) -> PyResult<bool> {
PyEq::eq(&self[..], &other[..], py)
}
}
impl<T> PyEq<PyAny> for T
where
for<'p> T: PyEq<T> + Clone + FromPyObject<'p>,
{
#[inline]
fn eq(&self, other: &PyAny, py: Python) -> PyResult<bool> {
let other_value: T = other.extract()?;
PyEq::eq(self, &other_value, py)
}
}
impl<K, V> PyEq<PyAny> for DictMap<K, V>
where
for<'p> K: PyEq<K> + Clone + pyo3::ToPyObject,
for<'p> V: PyEq<PyAny>,
{
#[inline]
fn eq(&self, other: &PyAny, py: Python) -> PyResult<bool> {
if other.len()? != self.len() {
return Ok(false);
}
for (key, value) in self {
match other.get_item(key) {
Ok(other_raw) => {
if !PyEq::eq(value, other_raw, py)? {
return Ok(false);
}
}
Err(ref err) if err.is_instance_of::<PyKeyError>(py) => {
return Ok(false);
}
Err(err) => return Err(err),
}
}
Ok(true)
}
}
trait PyDisplay {
fn str(&self, py: Python) -> PyResult<String>;
}
impl PyDisplay for PyObject {
fn str(&self, py: Python) -> PyResult<String> {
Ok(format!("{}", self.as_ref(py).str()?))
}
}
macro_rules! py_display_impl {
($($t:ty)*) => ($(
impl PyDisplay for $t {
fn str(&self, _: Python) -> PyResult<String> {
Ok(format!{"{}", self})
}
}
)*)
}
py_display_impl! {bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 BigUint}
macro_rules! py_display_tuple_impls {
( $($name:ident)+) => (
impl<$($name: PyDisplay),+> PyDisplay for ($($name,)+) where last_type!($($name,)+): ?Sized {
#[allow(non_snake_case)]
fn str(&self, py: Python) -> PyResult<String> {
let ($(ref $name,)+) = *self;
let mut str_vec: Vec<String> = Vec::new();
$(str_vec.push($name.str(py)?);)+
Ok(format!("({})", str_vec.join(", ")))
}
}
);
}
py_display_tuple_impls! { A }
py_display_tuple_impls! { A B }
py_display_tuple_impls! { A B C }
impl<A: PyDisplay> PyDisplay for [A] {
fn str(&self, py: Python) -> PyResult<String> {
let mut str_vec: Vec<String> = Vec::with_capacity(self.len());
for elem in self {
str_vec.push(elem.str(py)?);
}
Ok(format!("[{}]", str_vec.join(", ")))
}
}
macro_rules! py_display_array_impls {
($($N:expr)+) => {$(
impl<A: PyDisplay> PyDisplay for [A; $N] {
fn str(&self, py: Python) -> PyResult<String> {
self[..].str(py)
}
}
)+}
}
py_display_array_impls! {2 3}
impl<A: PyDisplay> PyDisplay for Vec<A> {
fn str(&self, py: Python) -> PyResult<String> {
self[..].str(py)
}
}
impl<K: PyDisplay, V: PyDisplay> PyDisplay for DictMap<K, V> {
fn str(&self, py: Python) -> PyResult<String> {
let mut str_vec: Vec<String> = Vec::with_capacity(self.len());
for elem in self {
str_vec.push(format!("{}: {}", elem.0.str(py)?, elem.1.str(py)?));
}
Ok(format!("{{{}}}", str_vec.join(", ")))
}
}
trait PyGCProtocol {
fn __traverse__(&self, _: PyVisit) -> Result<(), PyTraverseError> {
Ok(())
}
fn __clear__(&mut self) {}
}
#[derive(FromPyObject)]
enum SliceOrInt<'a> {
Int(isize),
Slice(&'a PySlice),
}
trait PyConvertToPyArray {
fn convert_to_pyarray(&self, py: Python) -> PyResult<PyObject>;
}
macro_rules! py_convert_to_py_array_impl {
($($t:ty)*) => ($(
impl PyConvertToPyArray for Vec<$t> {
fn convert_to_pyarray(&self, py: Python) -> PyResult<PyObject> {
Ok(self.clone().into_pyarray(py).into())
}
}
)*)
}
macro_rules! py_convert_to_py_array_obj_impl {
($t:ty) => {
impl PyConvertToPyArray for Vec<$t> {
fn convert_to_pyarray(&self, py: Python) -> PyResult<PyObject> {
let pyobj_vec: Vec<PyObject> = self.iter().map(|x| x.clone().into_py(py)).collect();
Ok(pyobj_vec.into_pyarray(py).into())
}
}
};
}
py_convert_to_py_array_impl! {usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64}
py_convert_to_py_array_obj_impl! {EdgeList}
py_convert_to_py_array_obj_impl! {(PyObject, Vec<PyObject>)}
impl PyConvertToPyArray for Vec<(usize, usize)> {
fn convert_to_pyarray(&self, py: Python) -> PyResult<PyObject> {
let mut mat = Array2::<usize>::from_elem((self.len(), 2), 0);
for (index, element) in self.iter().enumerate() {
mat[[index, 0]] = element.0;
mat[[index, 1]] = element.1;
}
Ok(mat.into_pyarray(py).into())
}
}
impl PyConvertToPyArray for Vec<(usize, usize, PyObject)> {
fn convert_to_pyarray(&self, py: Python) -> PyResult<PyObject> {
let mut mat = Array2::<PyObject>::from_elem((self.len(), 3), py.None());
for (index, element) in self.iter().enumerate() {
mat[[index, 0]] = element.0.into_py(py);
mat[[index, 1]] = element.1.into_py(py);
mat[[index, 2]] = element.2.clone();
}
Ok(mat.into_pyarray(py).into())
}
}
macro_rules! custom_vec_iter_impl {
($name:ident, $iter:ident, $reversed:ident, $data:ident, $T:ty, $doc:literal) => {
#[doc = $doc]
#[pyclass(module = "rustworkx", sequence)]
#[derive(Clone)]
pub struct $name {
pub $data: Vec<$T>,
}
#[pymethods]
impl $name {
#[new]
fn new() -> Self {
$name { $data: Vec::new() }
}
fn __getstate__(&self) -> Vec<$T> {
self.$data.clone()
}
fn __setstate__(&mut self, state: Vec<$T>) {
self.$data = state;
}
fn __richcmp__(&self, other: &PyAny, op: pyo3::basic::CompareOp) -> PyResult<bool> {
let compare = |other: &PyAny| -> PyResult<bool> {
Python::with_gil(|py| {
if other.len()? as usize != self.$data.len() {
return Ok(false);
}
for (i, item) in self.$data.iter().enumerate() {
let other_raw = other.get_item(i)?;
if !PyEq::eq(item, other_raw, py)? {
return Ok(false);
}
}
Ok(true)
})
};
match op {
pyo3::basic::CompareOp::Eq => compare(other),
pyo3::basic::CompareOp::Ne => match compare(other) {
Ok(res) => Ok(!res),
Err(err) => Err(err),
},
_ => Err(PyNotImplementedError::new_err("Comparison not implemented")),
}
}
fn __str__(&self) -> PyResult<String> {
Python::with_gil(|py| Ok(format!("{}{}", stringify!($name), self.$data.str(py)?)))
}
fn __hash__(&self) -> PyResult<u64> {
let mut hasher = DefaultHasher::new();
Python::with_gil(|py| PyHash::hash(&self.$data, py, &mut hasher))?;
Ok(hasher.finish())
}
fn __len__(&self) -> PyResult<usize> {
Ok(self.$data.len())
}
fn __getitem__(&self, py: Python, idx: SliceOrInt) -> PyResult<PyObject> {
match idx {
SliceOrInt::Slice(slc) => {
let len = self.$data.len().try_into().unwrap();
let indices = slc.indices(len)?;
let mut out_vec: Vec<$T> = Vec::new();
// Start and stop will always be positive the slice api converts
// negatives to the index for example:
// list(range(5))[-1:-3:-1]
// will return start=4, stop=2, and step=-1
let mut pos: isize = indices.start;
let mut cond = if indices.step < 0 {
pos > indices.stop
} else {
pos < indices.stop
};
while cond {
if pos < len as isize {
out_vec.push(self.$data[pos as usize].clone());
}
pos += indices.step;
if indices.step < 0 {
cond = pos > indices.stop;
} else {
cond = pos < indices.stop;
}
}
Ok(out_vec.into_py(py))
}
SliceOrInt::Int(idx) => {
let len = self.$data.len() as isize;
if idx >= len || idx < -len {
Err(PyIndexError::new_err(format!("Invalid index, {}", idx)))
} else if idx < 0 {
let len = self.$data.len();
Ok(self.$data[len - idx.abs() as usize].clone().into_py(py))
} else {
Ok(self.$data[idx as usize].clone().into_py(py))
}
}
}
}
fn __iter__(self_: Py<Self>, py: Python) -> $iter {
$iter {
inner: Some(self_.clone_ref(py)),
index: 0,
}
}
fn __reversed__(self_: Py<Self>, py: Python) -> $reversed {
$reversed {
inner: Some(self_.clone_ref(py)),
index: 0,
}
}
fn __array__(&self, py: Python, _dt: Option<&PyArrayDescr>) -> PyResult<PyObject> {
// Note: we accept the dtype argument on the signature but
// effictively do nothing with it to let Numpy handle the conversion itself
self.$data.convert_to_pyarray(py)
}
fn __traverse__(&self, vis: PyVisit) -> Result<(), PyTraverseError> {
PyGCProtocol::__traverse__(self, vis)
}
fn __clear__(&mut self) {
PyGCProtocol::__clear__(self)
}
}
#[doc = concat!("Custom iterator class for :class:`.", stringify!($name), "`")]
// No module because this isn't constructable from Python space, and is only exposed as an
// implementation detail.
#[pyclass]
pub struct $iter {
inner: Option<Py<$name>>,
index: usize,
}
#[pymethods]
impl $iter {
fn __next__(&mut self, py: Python) -> Option<Py<PyAny>> {
let data = self.inner.as_ref().unwrap().borrow(py);
if self.index < data.$data.len() {
let out = data.$data[self.index].clone().into_py(py);
self.index += 1;
Some(out)
} else {
None
}
}
fn __iter__(self_: Py<Self>) -> Py<Self> {
// Python iterators typically just return themselves from this, though in principle
// we could return a separate object that iterates starting from the same point.
self_
}
fn __length_hint__(&self, py: Python) -> usize {
self.inner
.as_ref()
.unwrap()
.borrow(py)
.$data
.len()
.saturating_sub(self.index)
}
fn __traverse__(&self, vis: PyVisit) -> Result<(), PyTraverseError> {
if let Some(obj) = self.inner.as_ref() {
vis.call(obj)?
}
Ok(())
}
fn __clear__(&mut self) {
self.inner = None;
}
}
#[doc = concat!("Custom reversed iterator class for :class:`.", stringify!($name), "`")]
// No module because this isn't constructable from Python space, and is only exposed as an
// implementation detail.
#[pyclass]
pub struct $reversed {
inner: Option<Py<$name>>,
index: usize,
}
#[pymethods]
impl $reversed {
fn __next__(&mut self, py: Python) -> Option<Py<PyAny>> {
let data = self.inner.as_ref().unwrap().borrow(py);
let len = data.$data.len();
if self.index < len {
let out = data.$data[len - self.index - 1].clone().into_py(py);
self.index += 1;
Some(out)
} else {
None
}
}
fn __iter__(self_: Py<Self>) -> Py<Self> {
// Python iterators typically just return themselves from this, though in principle
// we could return a separate object that iterates starting from the same point.
self_
}
fn __length_hint__(&self, py: Python) -> usize {
self.inner
.as_ref()
.unwrap()
.borrow(py)
.$data
.len()
.saturating_sub(self.index)
}
fn __traverse__(&self, vis: PyVisit) -> Result<(), PyTraverseError> {
if let Some(obj) = self.inner.as_ref() {
vis.call(obj)?
}
Ok(())
}
fn __clear__(&mut self) {
self.inner = None;
}
}
};
}
custom_vec_iter_impl!(
BFSSuccessors,
BFSSuccessorsIter,
BFSSuccessorsRev,
bfs_successors,
(PyObject, Vec<PyObject>),
"A custom class for the return from :func:`rustworkx.bfs_successors`
The class can is a read-only sequence of tuples of the form::
[(node, [successor_a, successor_b])]
where ``node``, ``successor_a``, and ``successor_b`` are the data payloads
for the nodes in the graph.
This class is a container class for the results of the
:func:`rustworkx.bfs_successors` function. It implements the Python
sequence protocol. So you can treat the return as read-only
sequence/list that is integer indexed. If you want to use it as an
iterator you can by wrapping it in an ``iter()`` that will yield the
results in order.
For example::
import rustworkx as rx
graph = rx.generators.directed_path_graph(5)
bfs_succ = rx.bfs_successors(0)
# Index based access
third_element = bfs_succ[2]
# Use as iterator
bfs_iter = iter(bfs_succ)
first_element = next(bfs_iter)
second_element = next(bfs_iter)
"
);
impl PyGCProtocol for BFSSuccessors {
fn __traverse__(&self, visit: PyVisit) -> Result<(), PyTraverseError> {
for node in &self.bfs_successors {
visit.call(&node.0)?;
for succ in &node.1 {
visit.call(succ)?;
}
}
Ok(())
}
fn __clear__(&mut self) {
self.bfs_successors = Vec::new();
}
}
custom_vec_iter_impl!(
BFSPredecessors,
BFSPredecessorsIter,
BFSPredecessorsRev,
bfs_predecessors,
(PyObject, Vec<PyObject>),
"A custom class for the return from :func:`rustworkx.bfs_predecessors`
The class can is a read-only sequence of tuples of the form::
[(node, [predecessor_a, predecessor_b])]
where ``node``, ``predecessor_a``, and ``predecessor_b`` are the data payloads
for the nodes in the graph.
This class is a container class for the results of the
:func:`rustworkx.bfs_predecessors` function. It implements the Python
sequence protocol. So you can treat the return as read-only
sequence/list that is integer indexed. If you want to use it as an
iterator you can by wrapping it in an ``iter()`` that will yield the
results in order.
For example::
import rustworkx as rx
graph = rx.generators.directed_path_graph(5)
bfs_succ = rx.bfs_predecessors(0)
# Index based access
third_element = bfs_succ[2]
# Use as iterator
bfs_iter = iter(bfs_succ)
first_element = next(bfs_iter)
second_element = next(bfs_iter)
"
);
impl PyGCProtocol for BFSPredecessors {
fn __traverse__(&self, visit: PyVisit) -> Result<(), PyTraverseError> {
for node in &self.bfs_predecessors {
visit.call(&node.0)?;
for succ in &node.1 {
visit.call(succ)?;
}
}
Ok(())
}
fn __clear__(&mut self) {
self.bfs_predecessors = Vec::new();
}
}
custom_vec_iter_impl!(
NodeIndices,
NodeIndicesIter,
NodeIndicesRev,
nodes,
usize,
"A custom class for the return of node indices
This class can be treated as a read-only sequence of integer node indices.
This class is a container class for the results of functions that
return a list of node indices. It implements the Python sequence
protocol. So you can treat the return as a read-only sequence/list
that is integer indexed. If you want to use it as an iterator you
can by wrapping it in an ``iter()`` that will yield the results in
order.
For example::
import rustworkx as rx
graph = rx.generators.directed_path_graph(5)
nodes = graph.node_indices()
# Index based access
third_element = nodes[2]
# Use as iterator
nodes_iter = iter(nodes)
first_element = next(nodes_iter)
second_element = next(nodes_iter)
"
);
impl PyGCProtocol for NodeIndices {}
custom_vec_iter_impl!(
EdgeList,
EdgeListIter,
EdgeListRev,
edges,
(usize, usize),
"A custom class for the return of edge lists
The class is a read-only sequence of tuples representing edge endpoints in
the form::
[(node_index_a, node_index_b)]
where ``node_index_a`` and ``node_index_b`` are the integer node indices of
the edge endpoints.
This class is a container class for the results of functions that
return a list of edges. It implements the Python sequence
protocol. So you can treat the return as a read-only sequence/list
that is integer indexed. If you want to use it as an iterator you
can by wrapping it in an ``iter()`` that will yield the results in
order.
For example::
import rustworkx as rx
graph = rx.generators.directed_path_graph(5)
edges = graph.edge_list()
# Index based access
third_element = edges[2]
# Use as iterator
edges_iter = iter(edges)
first_element = next(edges_iter)
second_element = next(edges_iter)
"
);
impl PyGCProtocol for EdgeList {}
custom_vec_iter_impl!(
WeightedEdgeList,
WeightedEdgeListIter,
WeightedEdgeListRev,
edges,
(usize, usize, PyObject),
"A custom class for the return of edge lists with weights
This class is a read-only sequence of tuples representing the edge
endpoints with the data payload for that edge in the form::
[(node_index_a, node_index_b, weight)]
where ``node_index_a`` and ``node_index_b`` are the integer node indices of
the edge endpoints and ``weight`` is the data payload of that edge.
This class is a container class for the results of functions that
return a list of edges with weights. It implements the Python sequence
protocol. So you can treat the return as a read-only sequence/list
that is integer indexed. If you want to use it as an iterator you
can by wrapping it in an ``iter()`` that will yield the results in
order.
For example::
import rustworkx as rx
graph = rx.generators.directed_path_graph(5)
edges = graph.weighted_edge_list()
# Index based access
third_element = edges[2]
# Use as iterator
edges_iter = iter(edges)
first_element = next(edges_iter)
second_element = next(edges_iter)
"
);
impl PyGCProtocol for WeightedEdgeList {
fn __traverse__(&self, visit: PyVisit) -> Result<(), PyTraverseError> {
for edge in &self.edges {
visit.call(&edge.2)?;
}
Ok(())
}
fn __clear__(&mut self) {
self.edges = Vec::new();
}
}
custom_vec_iter_impl!(
EdgeIndices,
EdgeIndicesIter,
EdgeIndicesRev,
edges,
usize,
"A custom class for the return of edge indices
The class is a read only sequence of integer edge indices.
This class is a container class for the results of functions that
return a list of edge indices. It implements the Python sequence
protocol. So you can treat the return as a read-only sequence/list
that is integer indexed. If you want to use it as an iterator you
can by wrapping it in an ``iter()`` that will yield the results in
order.
For example::
import rustworkx as rx
graph = rx.generators.directed_path_graph(5)
edges = rx.edge_indices()
# Index based access
third_element = edges[2]
# Use as iterator
edges_iter = iter(edges)
first_element = next(edges_iter)
second_element = next(edges_iter)
"
);
impl PyGCProtocol for EdgeIndices {}
impl PyHash for EdgeList {
fn hash<H: Hasher>(&self, py: Python, state: &mut H) -> PyResult<()> {
PyHash::hash(&self.edges, py, state)?;
Ok(())
}
}
impl PyEq<PyAny> for EdgeList {
#[inline]
fn eq(&self, other: &PyAny, py: Python) -> PyResult<bool> {
PyEq::eq(&self.edges, other, py)
}
}
impl PyDisplay for EdgeList {
fn str(&self, py: Python) -> PyResult<String> {
Ok(format!("EdgeList{}", self.edges.str(py)?))