I want a function that mutates the underlying String of a PathBuf object, but all I could achieve now is creation of a new object instead.
use std::path::{Path, PathBuf};
fn expanduser(path: &mut PathBuf) -> PathBuf {
return PathBuf::from(
&path
.to_str()
.unwrap()
.replace("~", PathBuf::home().to_str().unwrap()),
);
}
PathBuf wraps an OsString, not a String. They are much different types - String contains a UTF-8 string while OsString depends on the platform: arbitrary bytes for Unix and potentially-malformed UTF-16 on Windows.
You can use into_os_string to convert a PathBuf to an OsString, and From for the reverse.
If you are just trying to replace ~ with the home path, your best bet is to check if the first component (via the components method) is a Normal component containing "~" and join the rest of the components to the home path if so. There's crates that do this for you.
I hate that function, cause if the path I'm canonicalizing doesn't exist, it throws an error instead of gracefully doing what it should do. No one asked it to check existence.
You're likely misunderstanding the function. canonicalize resolves symlinks, so of course it won't work if the path doesn't exist. Also worth mentioning is that foo/bar/../baz is NOT necessarily the same as foo/baz, if foo/bar is a symlink.
I have a Vec<Vec<char>> as a console frame buffer.
I'd like to render the buffer, but it would make me to print!() every char. I would like to represent the inner &Vec<char> as &str (not converting, not making a new String, but just casting) to print it as a whole with print!().
Is it possible, or is print!() already as fast for many characters as print!() for a single string slice?
A &str represents a reference to a memory location where a string is stored encoded using UTF-8.
Since your Vec<char> is not a string encoded using UTF-8, there is no way around creating a new String in memory somewhere that you can then reference.
Luckily it's easy and fast to convert, if v is your Vec<char>, it's simply v.iter().cloned().collect::<String>(). If you no longer wish to keep the old v around, you can replace .iter().cloned() with .into_iter().
Given a std::path::Path, what's the most direct way to convert this to a null-terminated std::os::raw::c_char? (for passing to C functions that take a path).
use std::ffi::CString;
use std::os::raw::c_char;
use std::os::raw::c_void;
extern "C" {
some_c_function(path: *const c_char);
}
fn example_c_wrapper(path: std::path::Path) {
let path_str_c = CString::new(path.as_os_str().to_str().unwrap()).unwrap();
some_c_function(path_str_c.as_ptr());
}
Is there a way to avoid having so many intermediate steps?
Path -> OsStr -> &str -> CString -> as_ptr()
It's not as easy as it looks. There's one piece of information you didn't provide: what encoding is the C function expecting the path to be in?
On Linux, paths are "just" arrays of bytes (0 being invalid), and applications usually don't try to decode them. (However, they may have to decode them with a particular encoding to e.g. display them to the user, in which case they will usually try to decode them according to the current locale, which will often use the UTF-8 encoding.)
On Windows, it's more complicated, because there are variations of API functions that use an "ANSI" code page and variations that use "Unicode" (UTF-16). Additionally, Windows doesn't support setting UTF-8 as the "ANSI" code page. This means that unless the library specifically expects UTF-8 and converts path to the native encoding itself, passing it an UTF-8 encoded path is definitely wrong (though it might appear to work for strings containing only ASCII characters).
(I don't know about other platforms, but it's messy enough already.)
In Rust, Path is just a wrapper for OsStr. OsStr uses a platform-dependent representation that happens to be compatible with UTF-8 when the string is indeed valid UTF-8, but non-UTF-8 strings use an unspecified encoding (on Windows, it's actually using WTF-8, but this is not contractual; on Linux, it's just the array of bytes as is).
Before you pass a path to a C function, you must determine what encoding it's expecting the string to be in, and if it doesn't match Rust's encoding, you'll have to convert it before wrapping it in a CString. Rust doesn't let you convert a Path or an OsStr to anything other than a str in a platform-independent way. On Unix-based targets, the OsStrExt trait is available and provides access to the OsStr as a slice of bytes.
Rust used to provide a to_cstring method on OsStr, but it was never stabilized, and it was deprecated in Rust 1.6.0, as it was realized that the behavior was inappropriate for Windows (it returned an UTF-8 encoded path, but Windows APIs don't support that!).
As Path is just a thin wrapper around OsStr, you could nearly pass it as-is to your C function. But to be a valid C string we have to add the NUL terminating byte. Thus we must allocate a CString.
On the other hand, conversion to a str is both risky (what if the Path is not a valid UTF-8 string?) and an unnecessary cost: I use as_bytes() instead of to_str().
fn example_c_wrapper<P: AsRef<std::path::Path>>(path: P) {
let path_str_c = CString::new(path.as_ref().as_os_str().as_bytes()).unwrap();
some_c_function(path_str_c.as_ptr());
}
This is fo Unix. I do not know how it works for Windows.
If your goal is to convert a path to some sequence of bytes that is interpreted as a "native" path on whatever platform the code was compiled for, then the most direct way to do this is by using the OsStrExtof each platform you want to support:
let path = ..;
let mut buf = Vec::new();
#[cfg(unix)] {
use std::os::unix::ffi::OsStrExt;
buf.extend(path.as_os_str().as_bytes());
buf.push(0);
}
#[cfg(windows)] {
use std::os::windows::ffi::OsStrExt;
buf.extend(path.as_os_str()
.encode_wide()
.chain(Some(0))
.map(|b| {
let b = b.to_ne_bytes();
b.get(0).map(|s| *s).into_iter().chain(b.get(1).map(|s| *s))
})
.flatten());
}
This code[1] gives you a buffer of bytes that represents the path as a series of null-terminated bytes when you run it on linux, and represents "unicode" (utf16) when run on windows. You could add a fallback that converts OsStr to a str on other platforms, but I strongly recommend against that. (see why bellow)
For windows, you'll want to cast your buffer pointer to wchar_t * before using it with unicode functions on Windows (e.g. _wfopen). This code assumes that wchar_t is two bytes large, and that the buffer is properly aligned to wchar_ts.
On the Linux side, just use the pointer as-is.
About converting paths to unicode strings: Don't. Contrary to recommendations here and elsewhere, blindly converting a path to utf8 is not the correct way to handle a system path. Requiring that paths be valid unicode will cause your code to fail when (not if) it encounters paths that are not valid unicode. If you're handling real world paths, you will inevitably be handling non-utf8 paths. Doing it right the first time will help avoid a lot of pain and misery in the long run.
[1]: This code was taken directly out of a library I'm working on (feel free to reuse). It has been tested against both linux and 64-bit windows via wine.
If you are trying to produce a Vec<u8>, I usually phone it in and do:
#[cfg(unix)]
fn path_to_bytes<P: AsRef<Path>>(path: P) -> Vec<u8> {
use std::os::unix::ffi::OsStrExt;
path.as_ref().as_os_str().as_bytes().to_vec()
}
#[cfg(not(unix))]
fn path_to_bytes<P: AsRef<Path>>(path: P) -> Vec<u8> {
// On Windows, could use std::os::windows::ffi::OsStrExt to encode_wide(),
// but you end up with a Vec<u16> instead of a Vec<u8>, so that doesn't
// really help.
path.as_ref().to_string_lossy().to_string().into_bytes()
}
Knowing full well that non-UTF8 paths on non-UNIX will not be supported correctly. Note that you might need a Vec<u8> if working with Thrift/protocol buffers as opposed to a C API.
How does one convert a string to a lowercase or perform some kind of equivalency comparison ignoring case? There is an ignore case on the Ascii type but it seems convoluted and I don't see a way to convert str to Ascii.
std::ascii::AsciiExt.eq_ignore_ascii_case does what you want:
use std::ascii::AsciiExt;
fn main() {
assert!("foo".eq_ignore_ascii_case("FOO"));
}
(The search in the docs is quite good now; searches like "case" and "ascii" return good sets of results which contain this solution.)
From that same trait, std::ascii::StrAsciiExt.to_ascii_upper and std::ascii::StrAsciiExt.to_ascii_lower are also very handy.
String a = keyboard.nextLine().ignoreUpperCase()
is this a valid line?
It depends on your intention. The code you shared isn't clear about what you intend to do with the line you are reading from the keyboard.
Like it already has been suggested you could, in Java:
String a = keyboard.nextLine().toLowerCase();
or
String a = keyboard.nextLine().toUpperCase();
The intention here is that all lines you are getting are in upper or lower case. Ok if you want to treat all Strings you read from the keyboard as equals regardless of capitalization.
If your real intention is to match strings regardless of case, then the code reads better as:
String a = "Hello World";
a.equalsIgnoreCase("hello world");
now future maintainers of your code will understand what you're trying to do instead of trying to guess why you are converting to lower/upper case.