@@ -7,6 +7,7 @@ use chacha20poly1305::{
77} ;
88use lazy_static:: lazy_static;
99use pin_project:: pin_project;
10+ use rayon:: prelude:: * ;
1011use std:: cmp;
1112use std:: convert:: TryInto ;
1213use std:: io:: { self , Read , Seek , SeekFrom , Write } ;
@@ -51,9 +52,9 @@ impl Nonce {
5152 self . 0 = u128:: from ( val) << 8 ;
5253 }
5354
54- fn increment_counter ( & mut self ) {
55+ fn increment_counter ( & mut self , by : usize ) {
5556 // Increment the 11-byte counter
56- self . 0 += 1 << 8 ;
57+ self . 0 += ( by as u128 ) << 8 ;
5758 if self . 0 >> ( 8 * 12 ) != 0 {
5859 panic ! ( "We overflowed the nonce!" ) ;
5960 }
@@ -197,26 +198,29 @@ impl Stream {
197198 let num_chunks = chunks. len ( ) ;
198199 let mut encrypted = vec ! [ 0 ; chunks_len + TAG_SIZE * num_chunks] ;
199200
200- for ( i , ( encrypted , chunk ) ) in encrypted
201+ encrypted
201202 . chunks_mut ( ENCRYPTED_CHUNK_SIZE )
202203 . zip ( chunks)
203204 . enumerate ( )
204- {
205- if i + 1 == num_chunks {
206- self . nonce . set_last ( last) . unwrap ( ) ;
207- }
205+ . par_bridge ( )
206+ . for_each_with ( self . nonce , |nonce, ( i, ( encrypted, chunk) ) | {
207+ nonce. increment_counter ( i) ;
208+ if i + 1 == num_chunks {
209+ nonce. set_last ( last) . unwrap ( ) ;
210+ }
208211
209- let ( buffer, tag) = encrypted. split_at_mut ( chunk. len ( ) ) ;
210- buffer. copy_from_slice ( chunk) ;
211- tag. copy_from_slice (
212- self . aead
213- . encrypt_in_place_detached ( & self . nonce . to_bytes ( ) . into ( ) , & [ ] , buffer)
214- . expect ( "we will never hit chacha20::MAX_BLOCKS because of the chunk size" )
215- . as_slice ( ) ,
216- ) ;
212+ let ( buffer, tag) = encrypted. split_at_mut ( chunk. len ( ) ) ;
213+ buffer. copy_from_slice ( chunk) ;
214+ tag. copy_from_slice (
215+ self . aead
216+ . encrypt_in_place_detached ( & nonce. to_bytes ( ) . into ( ) , & [ ] , buffer)
217+ . expect ( "we will never hit chacha20::MAX_BLOCKS because of the chunk size" )
218+ . as_slice ( ) ,
219+ ) ;
220+ } ) ;
217221
218- self . nonce . increment_counter ( ) ;
219- }
222+ self . nonce . increment_counter ( num_chunks ) ;
223+ self . nonce . set_last ( last ) . unwrap ( ) ;
220224
221225 Ok ( encrypted)
222226 }
@@ -251,7 +255,7 @@ impl Stream {
251255 )
252256 . map_err ( |_| io:: Error :: new ( io:: ErrorKind :: InvalidData , "decryption error" ) ) ?;
253257
254- self . nonce . increment_counter ( ) ;
258+ self . nonce . increment_counter ( 1 ) ;
255259 }
256260
257261 Ok ( SecretVec :: new ( decrypted) )
0 commit comments