Strange bug when programming & small Qs

Cut in:
1.About vec initialization(fixed, confusing capacity with length)

//panic code
let mut ext_key:Vec<u32>=Vec::with_capacity(44);
ext_key[0..4].copy_from_slice( &key[0..4]);

i intend to initialize ext_key with fixed length by key, which means ext_key has key at the first four words and ext_key has fixed length. Codes below would panic at ext_key[0..4], saying range end index 4 out of range for slice of length 0,which means ext_key 's length is 0.
However, it would fix if i use

let mut ext_key:Vec<u32>=vec![0;44];
ext_key[0..4].copy_from_slice( &key[0..4]);

don't know why.
2. iter of for(fixed, both pass,false alarm)
intend to create a loop in a reverse order.

//panic codes
for round in (1..=9).rev(){}
//pass
for round in (1..10).rev(){}

3.About performance using threads(it depends?)
In AES using CBC, conventionally, each block is en/decoded one by one. Also, AES is a computing process. These means AES may take long time to en/decoding if only occupying one thread. So, i'm thinking, would it be better if each block is assigned to a thread to en/decode? Or ,would there be a way to optimize using threads?
4.About closure performance
Muti-nested closure ,muti-nested function and muti-calling function ,which is better?Muti-nested closure is ungly, i know and i'm using.
5.Managing test
My project's tree

.
├── Cargo.lock
├── Cargo.toml
├── src
    ├── lib
    │   └── aes.rs
    ├── lib.rs
    └── main.rs


i wrote public test function in aes.rs, but i can't figure how to manage tests, especially when the test function need to access local function in aes.rs.

//things in lib.rs
pub mod lib {
    pub mod aes;
}
// place for test funtion, haven't implemented
#[cfg(test)]
mod test{
    #[test]
    fn non(){
        
    }
}
//aes.rs    this is one test, don't know how to manage
pub fn unitied_test(mat:&mut Vec<u8>,key:&Vec<u32>){
//using private functions in aes.rs 
}

Vec::with_capacity() create an empty vector, but pre-allocate the storage on the heap so later push is guaranteed to not re-alloc before the capacity is full.

copy_from_slice() only copy, it doesn't grow. you can use Vec::extend_from_slice() in this situation.

3 Likes

You are confusing the capacity with the length.

This absolutely doesn't panic.

The only way to answer "which is faster" is to measure. (Anyway, modern compilers optimize aggressively, and there's usually no performance difference between similar structures written in different specific ways.)

3 Likes

seems i've got to fall in all pits to notice these minor things,thx

thx, maybe i complied before i saved where i devised