Can't figure out a weird Path behavior in Rust - file-io

I am writing a function that reads a Path and returns a DirEntry instance. There's some weird behaviour that I don't understand.
pub fn file_to_direntry<T: AsRef<Path>>(filepath: T) -> Result<DirEntry, Box<Error>> {
match filepath.has_parent() {
Some(parent) => {
//..
}
// has no parent
// this line would cause an error
// Err(Error { repr: Os { code: 2, message: "No such file or directory" } })
None => path_to_entry(Path::new("."), path),
}
}
fn path_to_entry<A: AsRef<Path>, B: AsRef<Path>>(path: A, filename: B) -> Result<DirEntry, Box<Error>> {
let filename: &Path = filename.as_ref();
let path: &Path = path.as_ref();
// this line prints, "" "."
println!("{:?} {:?}", path, PathBuf::from("."));
// when I replace this line to
// for entry in try!(read_dir(PathBuf::from(".")))
// it works perfectly fine
for entry in try!(read_dir(path)) {
println!("{:?}", try!(entry));
}
Err(From::from("no file found"))
}
Full code on the Rust playground

In your example code, you test with PathBuf::from("todos.txt"). This is a relative path, it does not include a starting / or c:\.
When you do let parent = pf.parent();, it will return Some(""). So the parent is an empty string, not Some("."), and also not None. parent will only return None if the path terminates in a root or prefix. In your example above, you only included the None part, but that will not be called.
read_dir will return an error if the provided path doesn't exist. That is the case when you pass an empty string like read_dir(PathBuf::from("")), but it works perfectly fine if you use read_dir(PathBuf::from(".")).

Related

Failed to fill whole buffer with rust read_exact

I have a little code snippet where I'm trying to write struct to a file and then read it. I have seen other similar posts where the asker has forgotten to zero initialise the buffer they are trying to read into. I have made sure not to do this, but I still am getting the error that 'failed to fill whole buffer' error when using read_exact, even though my buffer size and the size of the file I'm trying to read are the same.
Here is the code:
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use bincode::*;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct Node {
pub name: String,
end_ptr: u32 // number of bytes away the next node is
}
impl Node {
pub fn to_string(&self) -> String {
return self.name.clone();
}
}
fn main() {
let node = Node { name: String::from("node_1"), end_ptr: 0 };
let node_as_buf = bincode::serialize(&node).unwrap();
let len_of_bytes_serialised: usize = node_as_buf.len();
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open("test.txt")
.unwrap();
match file.write_all(&node_as_buf) {
Ok(result) => {println!("Write success")},
Err(err) => {println!("{}", &err)}
}
println!("{}", file.metadata().unwrap().len()); // this and
println!("{}", len_of_bytes_serialised); // this are the same size
let mut buffer = vec![0; len_of_bytes_serialised];
match file.read_exact(&mut buffer[..]) {
Ok(result) => println!("Read success"),
Err(err) => println!("{}", &err) // prints 'failed to fill whole buffer'
}
let read_node: Node = bincode::deserialize(&buffer[..]).unwrap();
}
Because you use the same stream for reading and writing, the cursor is moved to the end of the file and any reading will attempt to read there, which will of course fail. You can observe that if you'll print file.stream_position().
You need to rewind() before reading.

variable inspection error ?? IntelliJ IDEA 2021.3.3

I'm new in rust and i faced with some strange behavior of IDE IntelliJ IDEA 2021.3.3
I started from https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html and playing with IDE when i find that if i debug my code and shadowing the variable user_guess from String to u32 - variable inspector in IDE doesn't see that change and think that it is String
Does it looks like IDE bug, or what?
Full listing :
use rand::Rng;
use std::cmp::Ordering;
use std::{cmp, io};
fn main() {
println!("Lets play some game");
let ai_guess: u32 = rand::thread_rng().gen_range(0..=100);
loop {
let mut user_guess = String::new();
io::stdin().read_line(&mut user_guess).expect("Error");
let user_guess: u32 = match user_guess.trim().parse() {
Ok(num) => num,
Err(_) => 99
};
println!("{}",user_guess.to_string());
match user_guess.cmp(&ai_guess) {
Ordering::Less => { println!("You number is less then my") }
Ordering::Equal => {
println!("You WON!");
break;
}
Ordering::Greater => { println!("You bigger is less then my") }
}
};
}

How to get error using if else method in rust?

I know the idiomatic way to handle errors in rust is using match statement but I am looking for other ways to do the same.
use std::fs;
fn main() {
if let Ok(f) = fs::read_dir("/dummy"){
println!("First: {:?}", f);
}else{
println!("Error");
}
}
This works but I need the original Result error from fs::read_dir("/dummy") to be printed in the else statement. How can I do it?
Generally, I'd consider such an approach a bad idea, but you do have a few options, the most obvious two being "multiple if lets" and a "functional style" approach. I've included the match version for comparison. The code is available on the playground.
fn multiple_if_lets() {
let f = std::fs::read_dir("/dummy");
if let Ok(f) = &f {
println!("First: {:?}", f);
}
if let Err(f) = &f {
println!("Error: {:?}", f);
}
}
fn functional_style() {
std::fs::read_dir("/dummy")
.map(|f| println!("First: {:?}", f))
.unwrap_or_else(|f| println!("Error: {:?}", f));
}
fn match_style() {
match std::fs::read_dir("/dummy") {
Ok(f) => println!("First: {:?}", f),
Err(f) => println!("Error: {:?}", f),
}
}
I'm not quite sure why you don't want to use match because it is like a better if let! But you might find it useful to use an external crate like anyhow. You can very easily propagate all errors as one type and also add context where it makes sense.
In your Cargo.toml
[dependencies]
anyhow = "1"
In your code
use std::fs;
use anyhow::Context;
fn main() -> anyhow::Result<()> {
let dir = fs::read_dir("/dummy").context("failed to read dir")?;
// another fallible function which can return a `Result` with a
// different error type.
do_something(dir).context("failed to do something")?;
Ok(())
}
If read_dir had to fail here your program would exit and it would output the following
Error: failed to read dir
Caused by:
No such file or directory (os error 2)
If you wanted to throw away the error but still print it out you could still use match.
let dir = match fs::read_dir("/dummy").context("failed to read dir") {
Ok(dir) => Some(dir),
Err(err) => {
eprintln!("Error: {:?}", err);
None
}
};
This would output something like the following but still continue:
Error: failed to read dir
Caused by:
No such file or directory (os error 2)
Since Rust 1.65.0 (Nov. 2022), as mentioned by Mara Bos, you can do:
let Ok(f) = fs::read_dir("/dummy") else{ println!("Error"); return };
println!("First: {:?}", f);
let-else statements.
You can now write things like:
let Ok(a) = i32::from_str("123") else { return };
without needing an if or match statement.
This can be useful to avoid deeply nested if statements.

How to retrieve the underlying error from a Failure Error?

When trying to open a broken epub/ZIP file with epub-rs, the zip-rs crate error (which doesn't use Failure) is wrapped into a failure::Error by epub-rs. I want to handle each error type of zip-rs with an distinct error handler and need a way to match against the underlying error. How can I retrieve it from Failure?
fn main() {
match epub::doc::EpubDoc::new("a.epub") {
Ok(epub) => // do something with the epub
Err(error) => {
// handle errors
}
}
}
error.downcast::<zip::result::ZipError>() fails and error.downcast_ref() returns None.
You can downcast from a Failure Error into another type that implements Fail by using one of three functions:
downcast
downcast_ref
downcast_mut
use failure; // 0.1.5
use std::{fs, io};
fn generate() -> Result<(), failure::Error> {
fs::read_to_string("/this/does/not/exist")?;
Ok(())
}
fn main() {
match generate() {
Ok(_) => panic!("Should have an error"),
Err(e) => match e.downcast_ref::<io::Error>() {
Some(e) => println!("Got an io::Error: {}", e),
None => panic!("Could not downcast"),
},
}
}
For your specific case, I'm guessing that you are either running into mismatched dependency versions (see Why is a trait not implemented for a type that clearly has it implemented? for examples and techniques on how to track this down) or that you simply are getting the wrong error type. For example, a missing file is actually an std::io::Error:
// epub = "1.2.0"
// zip = "0.4.2"
// failure = "0.1.5"
use std::io;
fn main() {
if let Err(error) = epub::doc::EpubDoc::new("a.epub") {
match error.downcast_ref::<io::Error>() {
Some(i) => println!("IO error: {}", i),
None => {
panic!("Other error: {} {:?}", error, error);
}
}
}
}

How to include the file path in an IO error in Rust?

In this minimalist program, I'd like the file_size function to include the path /not/there in the Err so it can be displayed in the main function:
use std::fs::metadata;
use std::io;
use std::path::Path;
use std::path::PathBuf;
fn file_size(path: &Path) -> io::Result<u64> {
Ok(metadata(path)?.len())
}
fn main() {
if let Err(err) = file_size(&PathBuf::from("/not/there")) {
eprintln!("{}", err);
}
}
You must define your own error type in order to wrap this additional data.
Personally, I like to use the custom_error crate for that, as it's especially convenient for dealing with several types. In your case it might look like this:
use custom_error::custom_error;
use std::fs::metadata;
use std::io;
use std::path::{Path, PathBuf};
use std::result::Result;
custom_error! {ProgramError
Io {
source: io::Error,
path: PathBuf
} = #{format!("{path}: {source}", source=source, path=path.display())},
}
fn file_size(path: &Path) -> Result<u64, ProgramError> {
metadata(path)
.map(|md| md.len())
.map_err(|e| ProgramError::Io {
source: e,
path: path.to_path_buf(),
})
}
fn main() {
if let Err(err) = file_size(&PathBuf::from("/not/there")) {
eprintln!("{}", err);
}
}
Output:
/not/there: No such file or directory (os error 2)
While Denys Séguret's answer is correct, I like using my crate SNAFU because it provides the concept of a context. This makes the act of attaching the path (or anything else!) very easy to do:
use snafu::{ResultExt, Snafu}; // 0.2.3
use std::{
fs, io,
path::{Path, PathBuf},
};
#[derive(Debug, Snafu)]
enum ProgramError {
#[snafu(display("Could not get metadata for {}: {}", path.display(), source))]
Metadata { source: io::Error, path: PathBuf },
}
fn file_size(path: impl AsRef<Path>) -> Result<u64, ProgramError> {
let path = path.as_ref();
let md = fs::metadata(&path).context(Metadata { path })?;
Ok(md.len())
}
fn main() {
if let Err(err) = file_size("/not/there") {
eprintln!("{}", err);
}
}