fn open_new_file(file_name: PathBuf) -> io::Result<(PathBuf, File)> {
    fn try_open_new(file_name: &Path) -> io::Result<Option<File>> {
        match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(file_name)
        {
            Ok(file) => Ok(Some(file)),
            Err(err) if err.kind() == ErrorKind::AlreadyExists => Ok(None),
            Err(err) => Err(err),
        }
    }
    if let Some(file) = try_open_new(&file_name)? {
        return Ok((file_name, file));
    }
    for suffix in 1..u32::MAX {
        let candidate = {
            let mut candidate = file_name.clone().into_os_string();
            candidate.push(format!("-{}", suffix));
            PathBuf::from(candidate)
        };
        if let Some(file) = try_open_new(&candidate)? {
            return Ok((candidate, file));
        }
    }
    panic!("Could not create file after unreasonable number of attempts");
}
/// Find a file name that doesn't exist yet.
Find a file name that doesn't exist yet.
Find a file name that doesn ' t exist yet .
fn open_new_file(file_name: PathBuf) -> io::Result<(PathBuf, File)> {
    fn try_open_new(file_name: &Path) -> io::Result<Option<File>> {
        match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(file_name)
        {
            Ok(file) => Ok(Some(file)),
            Err(err) if err.kind() == ErrorKind::AlreadyExists => Ok(None),
            Err(err) => Err(err),
        }
    }
    if let Some(file) = try_open_new(&file_name)? {
        return Ok((file_name, file));
    }
    for suffix in 1..u32::MAX {
        let candidate = {
            let mut candidate = file_name.clone().into_os_string();
            candidate.push(format!("-{}", suffix));
            PathBuf::from(candidate)
        };
        if let Some(file) = try_open_new(&candidate)? {
            return Ok((candidate, file));
        }
    }
    panic!("Could not create file after unreasonable number of attempts");
}
fn open_new_file ( file_name : PathBuf ) -> io :: Result < ( PathBuf , File ) > { fn try_open_new ( file_name : & Path ) -> io :: Result < Option < File > > { match OpenOptions :: new ( ) . write ( true ) . create_new ( true ) . open ( file_name ) { Ok ( file ) => Ok ( Some ( file ) ) , Err ( err ) if err . kind ( ) == ErrorKind :: AlreadyExists => Ok ( None ) , Err ( err ) => Err ( err ) , } } if let Some ( file ) = try_open_new ( & file_name ) ? { return Ok ( ( file_name , file ) ) ; } for suffix in 1 .. u32 :: MAX { let candidate = { let mut candidate = file_name . clone ( ) . into_os_string ( ) ; candidate . push ( format ! ( " " suffix ) ) ; PathBuf :: from ( candidate ) } ; if let Some ( file ) = try_open_new ( & candidate ) ? { return Ok ( ( candidate , file ) ) ; } } panic ! ( " " ) ; }
Find a file name that doesn't exist yet.
Find a file name that doesn ' t exist yet .
file_name
PathBuf
file_name
PathBuf