Turning a OsStr into bytes

this is kind of a simple one, but i can't seem to find an answer. i have an application that encodes bytes into base64, and saves it as as a file's name. i now want to open the original file and decode the file name back into bytes. however, i can't seem to find a way to turn an OsString into bytes in order to decode it. can anyone help me out with this? thanks!

Does OsString::into_encoded_bytes or similar help?

1 Like

The problem with this is that it's quite difficult to use for serialization use cases, unless you have an application that is designed to only work with one particular type of platform. (e.g., "Unix only" or "Windows only".) For example, consider serializing a perfectly OsString like foo\xFFbar on Unix, and then deserializing it on Windows with from_encoded_bytes_unchecked. Ooops. UB. And in particular, the safety contract is even more narrow than that:

As the encoding is unspecified, callers must pass in bytes that originated as a mixture of validated UTF-8 and bytes from OsStr::as_encoded_bytes from within the same rust version built for the same target platform.

The function you linked, OsString::into_encoded_bytes, even explicitly warns against serializing:

For example, sending the bytes over the network or storing it in a file will likely result in incompatible data.

If possible, the simplest thing to do here is to require that the file paths are UTF-8. Then roundtripping them using safe and correct APIs is trivial. If there is a requirement to support all possible file paths, then there really is no one straight-forward platform independent way to deal with this. It depends on what you're trying to do.

3 Likes

yep... i couldn't find that in the docs. thanks

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.