1
1
use std:: { mem, raw} ;
2
2
use { IntrusiveIterator } ;
3
3
4
- impl < ' a , T > IntrusiveIterator < & ' a T > for & ' a [ T ] {
4
+ pub trait SliceIntrusiveIter < T > for Sized ? {
5
+ fn intrusive_iter ( & self ) -> Items < T > ;
6
+ fn intrusive_iter_mut ( & mut self ) -> ItemsMut < T > ;
7
+ }
8
+
9
+ pub struct Items < ' a , T : ' a > ( & ' a [ T ] ) ;
10
+ pub struct ItemsMut < ' a , T : ' a > ( & ' a mut [ T ] ) ;
11
+
12
+ impl < T > SliceIntrusiveIter < T > for [ T ] {
13
+ #[ inline]
14
+ fn intrusive_iter ( & self ) -> Items < T > { Items ( self ) }
15
+
16
+ #[ inline]
17
+ fn intrusive_iter_mut ( & mut self ) -> ItemsMut < T > { ItemsMut ( self ) }
18
+ }
19
+
20
+ impl < ' a , T > IntrusiveIterator < & ' a T > for Items < ' a , T > {
5
21
#[ inline]
6
22
fn traverse < F : FnMut ( & ' a T ) -> bool > ( self , mut f : F ) {
7
23
unsafe {
8
- let slice = mem:: transmute :: < & ' a [ T ] , raw:: Slice < T > > ( self ) ;
24
+ let slice = mem:: transmute :: < & ' a [ T ] , raw:: Slice < T > > ( self . 0 ) ;
9
25
10
26
let is_zero_size = mem:: size_of :: < T > ( ) == 0 ;
11
27
@@ -26,11 +42,11 @@ impl<'a, T> IntrusiveIterator<&'a T> for &'a [T] {
26
42
}
27
43
}
28
44
29
- impl < ' a , T > IntrusiveIterator < & ' a mut T > for & ' a mut [ T ] {
45
+ impl < ' a , T > IntrusiveIterator < & ' a mut T > for ItemsMut < ' a , T > {
30
46
#[ inline]
31
47
fn traverse < F : FnMut ( & ' a mut T ) -> bool > ( self , mut f : F ) {
32
48
unsafe {
33
- let slice = mem:: transmute :: < & ' a mut [ T ] , raw:: Slice < T > > ( self ) ;
49
+ let slice = mem:: transmute :: < & ' a mut [ T ] , raw:: Slice < T > > ( self . 0 ) ;
34
50
35
51
let is_zero_size = mem:: size_of :: < T > ( ) == 0 ;
36
52
@@ -59,13 +75,13 @@ mod test {
59
75
describe ! intrusive_slice_iter {
60
76
it "should yield all elements of a slice in order" {
61
77
let data = [ 1 u, 2 , 5 , 4 , 6 , 7 ] ;
62
- let intrusive: Vec <uint> = data. as_slice ( ) . map( |& x| x) . collect( ) ;
78
+ let intrusive: Vec <uint> = data. intrusive_iter ( ) . map( |& x| x) . collect( ) ;
63
79
assert_eq!( & * intrusive, data. as_slice( ) ) ;
64
80
}
65
81
66
82
it "should work with zero-sized types" {
67
83
let data = [ ( ) , ( ) , ( ) ] ;
68
- let intrusive: Vec <( ) > = data. as_slice ( ) . map( |& x| x) . collect( ) ;
84
+ let intrusive: Vec <( ) > = data. intrusive_iter ( ) . map( |& x| x) . collect( ) ;
69
85
assert_eq!( & * intrusive, data. as_slice( ) ) ;
70
86
}
71
87
@@ -74,7 +90,7 @@ mod test {
74
90
75
91
let data = Vec :: from_fn( 10000 , |_| random:: <uint>( ) ) ;
76
92
bench. iter( || {
77
- data. as_slice ( ) . iterate( |& : x| :: test:: black_box( x) ) ;
93
+ data. intrusive_iter ( ) . iterate( |& : x| :: test:: black_box( x) ) ;
78
94
} ) ;
79
95
}
80
96
0 commit comments