Skip to content

Add support for fallible sanitizers ? #185

@vic1707

Description

@vic1707

I have a new type wrapping a std:::fs::PathBuf, I'd like for it to always be an absolute path.
std::fs::canonicalize does exactly that but is fallible (io::Result<Pathbuf>).
Is it feasible to add support for fallible sanitizers? Currently I can work around that limitation by unwraping it but I'm not a fan 😓.

use derive_more::derive::Display;
use nutype::nutype;
use serde::{Deserialize, Serialize};
use std::{fs, io, path::{Path, PathBuf}};

#[nutype(
    derive(
        Debug, Clone, PartialEq, Eq, PartialOrd, Ord,
        Serialize, Deserialize
    ),
    sanitize(with = fs::canonicalize), // Errors since it returns a Result
    validate(with = is_file_and_exists, error = Error)
)]
struct File(PathBuf);

fn is_file_and_exists<P: AsRef<Path>>(path: P) -> Result<(), Error> {
    let path = path.as_ref();
    if !path.exists() {
        return Err(Error::IoError(io::ErrorKind::NotFound.into()));
    }
    if !path.is_file() {
        return Err(Error::NotAFile);
    }
    Ok(())
}

#[derive(Debug, Display, thiserror::Error)]
enum Error {
	#[display("{_0}")]
	IoError(#[from] io::Error),
	#[display("Provided path isn't a file.")]
	NotAFile,
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions