在字符串上创建读取流

Seb*_*edl 4 unit-testing rust

我有一个函数,它接受一个输入流,处理它的数据,然后返回一些东西,基本上是一个更复杂的版本:

fn read_number_from_stream(input: &mut io::BufRead) -> io::Result<u32> {
  // code that does something useful here
  Ok(0)
}
Run Code Online (Sandbox Code Playgroud)

现在我想为这个函数编写一个测试.

#[test]
fn input_with_zero_returns_zero() {
  let test_input = read_from_string("0\n");
  assert_eq!(Ok(0), read_number_from_stream(test_input));
}
Run Code Online (Sandbox Code Playgroud)

我该如何实施read_from_string?Rust的旧版本显然提供了std::io::mem::MemReader,但整个std::io::mem模块似乎在更新版本的Rust中消失了(我使用的是不稳定的1.5分支).

Fra*_*gné 6

每个特征的文档列出了可用的实现.这是文档页面BufRead.我们可以看到&'a [u8](一片字节)实现BufRead.我们可以从字符串中获取一个字节片段,并将一个可变引用传递给该片段read_number_from_stream:

use std::io;

fn read_number_from_stream(input: &mut io::BufRead) -> io::Result<u32> {
    // code that does something useful here
    Ok(0)
}

fn read_from_string(s: &str) -> &[u8] {
    s.as_bytes()
}

fn main() {
    let mut test_input = read_from_string("0\n");
    read_number_from_stream(&mut test_input);
}
Run Code Online (Sandbox Code Playgroud)

如果预期缓冲区不包含UTF-8,或者您只关心特定的ASCII兼容字符子集,则可能需要将测试输入定义为字节字符串,而不是普通字符串.字节字符串写成普通字符串,前缀为b例如b"0\n".字节串的类型是&[u8; N],字符串N的长度.由于该类型未实现BufRead,我们需要将其强制转换为&[u8].

fn main() {
    let mut test_input = b"0\n" as &[u8];
    read_number_from_stream(&mut test_input);
}
Run Code Online (Sandbox Code Playgroud)