11use crate :: data:: Error ;
2+ use std:: io;
23
34/// Helper for obtaining various information about pieces of a torrent.
45#[ derive( Debug ) ]
@@ -11,21 +12,32 @@ pub struct PieceInfo {
1112impl PieceInfo {
1213 /// Create new [`PieceInfo`] from an iterator over 20-bytes slices representing SHA-1 hashes of
1314 /// the pieces of a torrent.
14- pub fn new < ' a , I : Iterator < Item = & ' a [ u8 ] > > (
15+ pub fn new < ' a , I : Iterator < Item = & ' a [ u8 ; 20 ] > > (
1516 piece_it : I ,
1617 piece_length : usize ,
1718 total_length : usize ,
18- ) -> Self {
19- fn to_20_byte_array ( slice : & [ u8 ] ) -> [ u8 ; 20 ] {
20- let mut ret = [ 0u8 ; 20 ] ;
21- ret . copy_from_slice ( slice ) ;
22- ret
19+ ) -> Result < Self , Error > {
20+ if piece_length == 0 {
21+ return Err (
22+ io :: Error :: new ( io :: ErrorKind :: InvalidInput , "piece length cannot be zero" ) . into ( )
23+ ) ;
2324 }
24- PieceInfo {
25- pieces : piece_it. map ( to_20_byte_array) . collect ( ) ,
25+ if total_length == 0 {
26+ return Err (
27+ io:: Error :: new ( io:: ErrorKind :: InvalidInput , "total length cannot be zero" ) . into ( )
28+ ) ;
29+ }
30+ let pieces: Vec < [ u8 ; 20 ] > = piece_it. cloned ( ) . collect ( ) ;
31+ if pieces. len ( ) != total_length. div_ceil ( piece_length) {
32+ return Err (
33+ io:: Error :: new ( io:: ErrorKind :: InvalidInput , "unexpected number of pieces" ) . into ( )
34+ ) ;
35+ }
36+ Ok ( PieceInfo {
37+ pieces,
2638 piece_length,
2739 total_length,
28- }
40+ } )
2941 }
3042
3143 /// Get global offset relative to the start of the entire torrent (a single entity possibly
@@ -78,7 +90,7 @@ mod tests {
7890
7991 #[ test]
8092 fn last_incomplete_piece_is_handled_correctly ( ) {
81- let p = PieceInfo :: new ( std:: iter:: repeat_n ( [ 0u8 ; 20 ] . as_slice ( ) , 3 ) , 5 , 12 ) ;
93+ let p = PieceInfo :: new ( std:: iter:: repeat_n ( & [ 0u8 ; 20 ] , 3 ) , 5 , 12 ) . unwrap ( ) ;
8294 assert_eq ! ( 3 , p. piece_count( ) ) ;
8395 assert_eq ! ( 5 , p. piece_len( 0 ) ) ;
8496 assert_eq ! ( 5 , p. piece_len( 1 ) ) ;
0 commit comments