Fix CratesToml::load_from_reader: Ret default for empty reader (#622)

Fixed #621

Also add a new unit test for this bug.

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
Jiahao XU 2022-12-28 11:31:47 +11:00 committed by GitHub
parent 6bdb26930e
commit c87d42d2d8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -49,7 +49,12 @@ impl CratesToml<'_> {
pub fn load_from_reader<R: io::Read>(mut reader: R) -> Result<Self, CratesTomlParseError> {
let mut vec = Vec::new();
reader.read_to_end(&mut vec)?;
Ok(toml::from_slice(&vec)?)
if vec.is_empty() {
Ok(Self::default())
} else {
toml::from_slice(&vec).map_err(CratesTomlParseError::from)
}
}
pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self, CratesTomlParseError> {
@ -246,6 +251,16 @@ mod tests {
);
}
#[test]
fn test_empty_file() {
let tempdir = TempDir::new().unwrap();
let path = tempdir.path().join("crates-v1.toml");
File::create(&path).unwrap();
assert!(CratesToml::load_from_path(&path).unwrap().v1.is_empty());
}
#[test]
fn test_loading() {
let raw_data = br#"