@@ -77,7 +77,7 @@ pub(crate) fn encode_with_padding<E: Engine + ?Sized>(
77
77
let b64_bytes_written = engine. internal_encode ( input, output) ;
78
78
79
79
let padding_bytes = if engine. config ( ) . encode_padding ( ) {
80
- add_padding ( input . len ( ) , & mut output[ b64_bytes_written..] )
80
+ add_padding ( b64_bytes_written , & mut output[ b64_bytes_written..] )
81
81
} else {
82
82
0
83
83
} ;
@@ -117,20 +117,20 @@ pub fn encoded_len(bytes_len: usize, padding: bool) -> Option<usize> {
117
117
}
118
118
119
119
/// Write padding characters.
120
- /// `input_len ` is the size of the original, not encoded, input .
120
+ /// `unpadded_output_len ` is the size of the unpadded but base64 encoded data .
121
121
/// `output` is the slice where padding should be written, of length at least 2.
122
122
///
123
123
/// Returns the number of padding bytes written.
124
- pub ( crate ) fn add_padding ( input_len : usize , output : & mut [ u8 ] ) -> usize {
125
- // TODO base on encoded len to use cheaper mod by 4 (aka & 7)
126
- let rem = input_len % 3 ;
127
- let mut bytes_written = 0 ;
128
- for _ in 0 .. ( ( 3 - rem ) % 3 ) {
129
- output [ bytes_written ] = PAD_BYTE ;
130
- bytes_written += 1 ;
124
+ pub ( crate ) fn add_padding ( unpadded_output_len : usize , output : & mut [ u8 ] ) -> usize {
125
+ let pad_bytes = ( 4 - ( unpadded_output_len % 4 ) ) % 4 ;
126
+ // for just a couple bytes, this has better performance than using
127
+ // .fill(), or iterating over mutable refs, which call memset()
128
+ # [ allow ( clippy :: needless_range_loop ) ]
129
+ for i in 0 ..pad_bytes {
130
+ output [ i ] = PAD_BYTE ;
131
131
}
132
132
133
- bytes_written
133
+ pad_bytes
134
134
}
135
135
136
136
/// Errors that can occur while encoding into a slice.
@@ -434,18 +434,18 @@ mod tests {
434
434
435
435
let mut rng = rand:: rngs:: SmallRng :: from_entropy ( ) ;
436
436
437
- // cover our bases for length % 3
438
- for input_len in 0 ..10 {
437
+ // cover our bases for length % 4
438
+ for unpadded_output_len in 0 ..20 {
439
439
output. clear ( ) ;
440
440
441
441
// fill output with random
442
- for _ in 0 ..10 {
442
+ for _ in 0 ..100 {
443
443
output. push ( rng. gen ( ) ) ;
444
444
}
445
445
446
446
let orig_output_buf = output. clone ( ) ;
447
447
448
- let bytes_written = add_padding ( input_len , & mut output) ;
448
+ let bytes_written = add_padding ( unpadded_output_len , & mut output) ;
449
449
450
450
// make sure the part beyond bytes_written is the same garbage it was before
451
451
assert_eq ! ( orig_output_buf[ bytes_written..] , output[ bytes_written..] ) ;
0 commit comments