RUST中Read trait在文件流和网络流中对read方法不同的implement

2020-11-28

1. buf远大于内容

use std::fs::File;
use std::io::Read;

fn main(){
    //abcd1234
    let mut f = File::open("/home/tyrell/A-backgulf/test");
    match f {
        Ok(mut file)=>{
            println!("打开文件成功");
            let mut buf = [0u8;80];
            let i = file.read(&mut buf);
            println!("{}",i.unwrap());//8

            let i = file.read(&mut buf);
            println!("{}",i.unwrap());//0 再读也都还是0
        }
        Err(err)=>{
            println!("打开文件失败")
        }
    }
}

2. buf正好等于内容

同1,读取结果返回长度,再读返回0

3. buf远小于内容

多次读满,最后一次读完,再读返回0

4. buf远小于内容且buf*n == content.length

多次读完后 返回0

对于fs模块下,

总结:尽量读,每次返回读取长度;读完再读返回 0;不会阻塞。


 

https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read

Pull some bytes from this source into the specified buffer, returning how many bytes were read.
 

This function does not provide any guarantees about whether it blocks waiting for data, but if an object needs to block for a read and cannot, it will typically signal this via an Err return value.
 

If the return value of this method is Ok(n), then it must be guaranteed that 0 <= n <= buf.len(). A nonzero n value indicates that the buffer buf has been filled in with n bytes of data from this source. If n is 0, then it can indicate one of two scenarios:


 

This reader has reached its "end of file" and will likely no longer be able to produce bytes. Note that this does not mean that the reader will always no longer be able to produce bytes.

The buffer specified was 0 bytes in length.

 

对于net模块下,

需要阻塞但是不能阻塞到数据时返回Err???还不是要··保证这个方法是阻塞的··吗?即便是对方关闭连接这边不能继续在这个流上read(报Err此处合理)。就我写的demo来说,C端不发东西,S这边是一直阻塞在read这儿的。所以可以用读取到0长度当做通信关闭,Err当做 不合理关闭