Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vec<PathBuf> to &[&Path] without allocations?

I have function that return Vec<PathBuf> and function that accept &[&Path], basically like this:

use std::path::{Path, PathBuf};

fn f(paths: &[&Path]) {
}

fn main() {
    let a: Vec<PathBuf> = vec![PathBuf::from("/tmp/a.txt"), PathBuf::from("/tmp/b.txt")];

    f(&a[..]);
}

Is it possible to convert Vec<PathBuf> to &[&Path] without memory allocations?

If not, how should I change f signature to accept slices with Path and PathBuf?

like image 560
user1244932 Avatar asked Jul 26 '26 08:07

user1244932


1 Answers

Is it possible to convert Vec<PathBuf> to &[&Path] without memory allocations?

No, as answered by How do I write a function that takes both owned and non-owned string collections?; a PathBuf and a Path have different memory layouts (the answer uses String and str; the concepts are the same).

how should I change f signature to accept slices with Path and PathBuf?

Again as suggested in How do I write a function that takes both owned and non-owned string collections?, use AsRef:

use std::path::{Path, PathBuf};

fn f<P>(paths: &[P])
    where P: AsRef<Path>
{}

fn main() {
    let a = vec![PathBuf::from("/tmp/a.txt")];
    let b = vec![Path::new("/tmp/b.txt")];

    f(&a);
    f(&b);
}

This requires no additional heap allocation.

like image 144
Shepmaster Avatar answered Jul 28 '26 20:07

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!