Append an additional extension?


#1

Let’s say I have a Path: foo.bar, and I’d like to append an extension baz to get: foo.bar.baz. Right now there seem to be no easy way to do it.


#2

Remember that Path is analogous to str and that PathBuf is likewise analogous to String, and you can build on it.


#3

How? I can’t format! or append_str to a PathBuf. Everything is working on component level, plus couple of methods for extension and file stem. Am I missing something?


#4

Well, if you want it in your format, then you can push and then replace on a .to_string call to replace / with .. I’m on mobile so I can’t add a playground example


#5

No. I want a PathBuf. I need to rename a directory to a ${original_dir}.tmp, but the original_dir might already have dots in it.


#6

Why not try the following:

  1. Get the last component in path_buf.components() and cast it’s as_os_str to an owned string
  2. Add what you want to it
  3. Call pop on path_buf
  4. Push your new string onto your path_buf

This is missing a check to make sure that it is a directory, so be sure that it either is, or run some checks on user input
Edit: it’s actually abit more complicated than that because it doesn’t go straight to String and instead its os variant, so that’s something to keep in mind


#7

Yeah, so I have something like this, but it’s terribly clunky. I’m surprised that stdlib provided methods to replace the extension, but not append, which is usually what I would actually like (eg. for tmp files etc)


#8

Oh, what about a cleaner way where you call into_os_string on the pathbuf and just append and form a new pathbuf?
I know that this isn’t very non-clunky but I can’t figure out another way without some better context


#9

How do you append to OsString without converting to Vec<u8>?


#10

You can push as better exemplified by the examples on the docs


#11

I’ve totally missed it. Thank you!