Read an arbitrary number of bytes from type implementing Read

后端 未结 3 1376
南旧
南旧 2021-01-13 08:33

I have something that is Read; currently it\'s a File. I want to read a number of bytes from it that is only known at runtime (length prefix in a b

3条回答
  •  隐瞒了意图╮
    2021-01-13 09:39

    Like the Iterator adaptors, the IO adaptors take self by value to be as efficient as possible. Also like the Iterator adaptors, a mutable reference to a Read is also a Read.

    To solve your problem, you just need Read::by_ref:

    use std::io::Read;
    use std::fs::File;
    
    fn main() {
        let mut file = File::open("/etc/hosts").unwrap();
        let length = 5;
    
        let mut vec = Vec::with_capacity(length);
        file.by_ref().take(length as u64).read_to_end(&mut vec).unwrap();
    
        let mut the_rest = Vec::new();
        file.read_to_end(&mut the_rest).unwrap();
    }
    

提交回复
热议问题