Home > other >  How to generalize a function to accept file path or file contents as string?
How to generalize a function to accept file path or file contents as string?

Time:09-27

I'm writing a file parser that parses ".toml" files (using the toml-rs crate) into Rust data types. Right now my function accepts PathBuf for the file path. I want to make it generic so that it can accept any type of source that contains TOML:

  1. File paths, PathBuf or Path.
  2. String that has toml data in it.

Is it possible to achieve this?

CodePudding user response:

There's not going to be a good generic trait that's implement by both String and PathBuf they are too different. One is the content and one is a path to the content.

You could have two entry point functions one accepting a path/buf and one accepting a string (that then call the same helper)

pub fn parse_from_file<P: AsRef<Path>>(path: P) -> Toml {
    let content = std::fs::read_to_string(path);
    parse(content)
}
pub fn parse(content: String) -> Toml {
    todo!();
}

Or you could use an enum like this:

enum ParseContent {
    PathBuf(PathBuf),
    Path(Path),
    Content(String)
}

pub fn parse(source: ParseContent) -> Toml { todo!() }

I prefer the first.

  • Related