pub struct OsStr { /* private fields */ }
Expand description
A UTF-8-encoded fixed string
NOTE: To support dynamic values (i.e. OsString
), enable the string
feature
Implementations§
source§impl OsStr
impl OsStr
sourcepub fn as_os_str(&self) -> &OsStr
pub fn as_os_str(&self) -> &OsStr
Get the raw string as an std::ffi::OsStr
Examples found in repository?
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
pub fn to_os_string(&self) -> std::ffi::OsString {
self.as_os_str().to_owned()
}
}
impl From<&'_ OsStr> for OsStr {
fn from(id: &'_ OsStr) -> Self {
id.clone()
}
}
#[cfg(feature = "string")]
impl From<Str> for OsStr {
fn from(id: Str) -> Self {
match id.into_inner() {
crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)),
crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())),
}
}
}
#[cfg(not(feature = "string"))]
impl From<Str> for OsStr {
fn from(id: Str) -> Self {
Self::from_static_ref(std::ffi::OsStr::new(id.into_inner().0))
}
}
#[cfg(feature = "perf")]
impl From<&'_ Str> for OsStr {
fn from(id: &'_ Str) -> Self {
match id.clone().into_inner() {
crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)),
crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())),
}
}
}
impl From<&'_ Str> for OsStr {
fn from(id: &'_ Str) -> Self {
id.clone().into()
}
}
#[cfg(feature = "string")]
impl From<std::ffi::OsString> for OsStr {
fn from(name: std::ffi::OsString) -> Self {
Self::from_string(name)
}
}
#[cfg(feature = "string")]
impl From<&'_ std::ffi::OsString> for OsStr {
fn from(name: &'_ std::ffi::OsString) -> Self {
Self::from_ref(name.as_os_str())
}
}
#[cfg(feature = "string")]
impl From<std::string::String> for OsStr {
fn from(name: std::string::String) -> Self {
Self::from_string(name.into())
}
}
#[cfg(feature = "string")]
impl From<&'_ std::string::String> for OsStr {
fn from(name: &'_ std::string::String) -> Self {
Self::from_ref(name.as_str().as_ref())
}
}
impl From<&'static std::ffi::OsStr> for OsStr {
fn from(name: &'static std::ffi::OsStr) -> Self {
Self::from_static_ref(name)
}
}
impl From<&'_ &'static std::ffi::OsStr> for OsStr {
fn from(name: &'_ &'static std::ffi::OsStr) -> Self {
Self::from_static_ref(name)
}
}
impl From<&'static str> for OsStr {
fn from(name: &'static str) -> Self {
Self::from_static_ref(name.as_ref())
}
}
impl From<&'_ &'static str> for OsStr {
fn from(name: &'_ &'static str) -> Self {
Self::from_static_ref((*name).as_ref())
}
}
impl From<OsStr> for std::ffi::OsString {
fn from(name: OsStr) -> Self {
name.name.into_os_string()
}
}
impl From<OsStr> for std::path::PathBuf {
fn from(name: OsStr) -> Self {
std::ffi::OsString::from(name).into()
}
}
impl std::fmt::Debug for OsStr {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self.as_os_str(), f)
}
}
impl std::ops::Deref for OsStr {
type Target = std::ffi::OsStr;
#[inline]
fn deref(&self) -> &std::ffi::OsStr {
self.as_os_str()
}
}
impl AsRef<std::ffi::OsStr> for OsStr {
#[inline]
fn as_ref(&self) -> &std::ffi::OsStr {
self.as_os_str()
}
}
impl AsRef<std::path::Path> for OsStr {
#[inline]
fn as_ref(&self) -> &std::path::Path {
std::path::Path::new(self)
}
}
impl std::borrow::Borrow<std::ffi::OsStr> for OsStr {
#[inline]
fn borrow(&self) -> &std::ffi::OsStr {
self.as_os_str()
}
}
impl PartialEq<str> for OsStr {
#[inline]
fn eq(&self, other: &str) -> bool {
PartialEq::eq(self.as_os_str(), other)
}
}
impl PartialEq<OsStr> for str {
#[inline]
fn eq(&self, other: &OsStr) -> bool {
PartialEq::eq(self, other.as_os_str())
}
}
impl PartialEq<&'_ str> for OsStr {
#[inline]
fn eq(&self, other: &&str) -> bool {
PartialEq::eq(self.as_os_str(), *other)
}
}
impl PartialEq<OsStr> for &'_ str {
#[inline]
fn eq(&self, other: &OsStr) -> bool {
PartialEq::eq(*self, other.as_os_str())
}
}
impl PartialEq<&'_ std::ffi::OsStr> for OsStr {
#[inline]
fn eq(&self, other: &&std::ffi::OsStr) -> bool {
PartialEq::eq(self.as_os_str(), *other)
}
}
impl PartialEq<OsStr> for &'_ std::ffi::OsStr {
#[inline]
fn eq(&self, other: &OsStr) -> bool {
PartialEq::eq(*self, other.as_os_str())
}
}
impl PartialEq<std::string::String> for OsStr {
#[inline]
fn eq(&self, other: &std::string::String) -> bool {
PartialEq::eq(self.as_os_str(), other.as_str())
}
}
impl PartialEq<OsStr> for std::string::String {
#[inline]
fn eq(&self, other: &OsStr) -> bool {
PartialEq::eq(self.as_str(), other.as_os_str())
}
}
impl PartialEq<std::ffi::OsString> for OsStr {
#[inline]
fn eq(&self, other: &std::ffi::OsString) -> bool {
PartialEq::eq(self.as_os_str(), other.as_os_str())
}
}
impl PartialEq<OsStr> for std::ffi::OsString {
#[inline]
fn eq(&self, other: &OsStr) -> bool {
PartialEq::eq(self.as_os_str(), other.as_os_str())
}
More examples
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
fn react(
&self,
ident: Option<Identifier>,
source: ValueSource,
arg: &Arg,
mut raw_vals: Vec<OsString>,
mut trailing_idx: Option<usize>,
matcher: &mut ArgMatcher,
) -> ClapResult<ParseResult> {
ok!(self.resolve_pending(matcher));
debug!(
"Parser::react action={:?}, identifier={:?}, source={:?}",
arg.get_action(),
ident,
source
);
// Process before `default_missing_values` to avoid it counting as values from the command
// line
if source == ValueSource::CommandLine {
ok!(self.verify_num_args(arg, &raw_vals));
}
if raw_vals.is_empty() {
// We assume this case is valid: require equals, but min_vals == 0.
if !arg.default_missing_vals.is_empty() {
debug!("Parser::react: has default_missing_vals");
trailing_idx = None;
raw_vals.extend(
arg.default_missing_vals
.iter()
.map(|s| s.as_os_str().to_owned()),
);
}
}
if let Some(val_delim) = arg.get_value_delimiter() {
if self.cmd.is_dont_delimit_trailing_values_set() && trailing_idx == Some(0) {
// Nothing to do
} else {
let mut split_raw_vals = Vec::with_capacity(raw_vals.len());
for (i, raw_val) in raw_vals.into_iter().enumerate() {
let raw_val = RawOsString::new(raw_val);
if !raw_val.contains(val_delim)
|| (self.cmd.is_dont_delimit_trailing_values_set()
&& trailing_idx == Some(i))
{
split_raw_vals.push(raw_val.into_os_string());
} else {
split_raw_vals
.extend(raw_val.split(val_delim).map(|x| x.to_os_str().into_owned()));
}
}
raw_vals = split_raw_vals
}
}
match arg.get_action() {
ArgAction::Set => {
if source == ValueSource::CommandLine
&& matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
{
// Record flag's index
self.cur_idx.set(self.cur_idx.get() + 1);
debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
}
if matcher.remove(arg.get_id())
&& !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
{
return Err(ClapError::argument_conflict(
self.cmd,
arg.to_string(),
vec![arg.to_string()],
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
debug!(
"Parser::react not enough values passed in, leaving it to the validator to complain",
);
}
Ok(ParseResult::ValuesDone)
}
ArgAction::Append => {
if source == ValueSource::CommandLine
&& matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
{
// Record flag's index
self.cur_idx.set(self.cur_idx.get() + 1);
debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
}
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
debug!(
"Parser::react not enough values passed in, leaving it to the validator to complain",
);
}
Ok(ParseResult::ValuesDone)
}
ArgAction::SetTrue => {
let raw_vals = if raw_vals.is_empty() {
vec![OsString::from("true")]
} else {
raw_vals
};
if matcher.remove(arg.get_id())
&& !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
{
return Err(ClapError::argument_conflict(
self.cmd,
arg.to_string(),
vec![arg.to_string()],
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
Ok(ParseResult::ValuesDone)
}
ArgAction::SetFalse => {
let raw_vals = if raw_vals.is_empty() {
vec![OsString::from("false")]
} else {
raw_vals
};
if matcher.remove(arg.get_id())
&& !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
{
return Err(ClapError::argument_conflict(
self.cmd,
arg.to_string(),
vec![arg.to_string()],
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
Ok(ParseResult::ValuesDone)
}
ArgAction::Count => {
let raw_vals = if raw_vals.is_empty() {
let existing_value = *matcher
.get_one::<crate::builder::CountType>(arg.get_id().as_str())
.unwrap_or(&0);
let next_value = existing_value.saturating_add(1);
vec![OsString::from(next_value.to_string())]
} else {
raw_vals
};
matcher.remove(arg.get_id());
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
Ok(ParseResult::ValuesDone)
}
ArgAction::Help => {
let use_long = match ident {
Some(Identifier::Long) => true,
Some(Identifier::Short) => false,
Some(Identifier::Index) => true,
None => true,
};
debug!("Help: use_long={}", use_long);
Err(self.help_err(use_long))
}
ArgAction::Version => {
let use_long = match ident {
Some(Identifier::Long) => true,
Some(Identifier::Short) => false,
Some(Identifier::Index) => true,
None => true,
};
debug!("Version: use_long={}", use_long);
Err(self.version_err(use_long))
}
}
}
sourcepub fn to_os_string(&self) -> OsString
pub fn to_os_string(&self) -> OsString
Get the raw string as an OsString
Examples found in repository?
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
fn add_default_value(&self, arg: &Arg, matcher: &mut ArgMatcher) -> ClapResult<()> {
if !arg.default_vals_ifs.is_empty() {
debug!("Parser::add_default_value: has conditional defaults");
if !matcher.contains(arg.get_id()) {
for (id, val, default) in arg.default_vals_ifs.iter() {
let add = if let Some(a) = matcher.get(id) {
match val {
crate::builder::ArgPredicate::Equals(v) => {
a.raw_vals_flatten().any(|value| v == value)
}
crate::builder::ArgPredicate::IsPresent => true,
}
} else {
false
};
if add {
if let Some(default) = default {
let arg_values = vec![default.to_os_string()];
let trailing_idx = None;
let _ = ok!(self.react(
None,
ValueSource::DefaultValue,
arg,
arg_values,
trailing_idx,
matcher,
));
}
return Ok(());
}
}
}
} else {
debug!("Parser::add_default_value: doesn't have conditional defaults");
}
if !arg.default_vals.is_empty() {
debug!(
"Parser::add_default_value:iter:{}: has default vals",
arg.get_id()
);
if matcher.contains(arg.get_id()) {
debug!("Parser::add_default_value:iter:{}: was used", arg.get_id());
// do nothing
} else {
debug!(
"Parser::add_default_value:iter:{}: wasn't used",
arg.get_id()
);
let arg_values: Vec<_> = arg
.default_vals
.iter()
.map(crate::builder::OsStr::to_os_string)
.collect();
let trailing_idx = None;
let _ = ok!(self.react(
None,
ValueSource::DefaultValue,
arg,
arg_values,
trailing_idx,
matcher,
));
}
} else {
debug!(
"Parser::add_default_value:iter:{}: doesn't have default vals",
arg.get_id()
);
// do nothing
}
Ok(())
}
Methods from Deref<Target = OsStr>§
1.0.0 · sourcepub fn to_string_lossy(&self) -> Cow<'_, str>
pub fn to_string_lossy(&self) -> Cow<'_, str>
Converts an OsStr
to a Cow<str>
.
Any non-Unicode sequences are replaced with
U+FFFD REPLACEMENT CHARACTER
.
Examples
Calling to_string_lossy
on an OsStr
with invalid unicode:
// Note, due to differences in how Unix and Windows represent strings,
// we are forced to complicate this example, setting up example `OsStr`s
// with different source data and via different platform extensions.
// Understand that in reality you could end up with such example invalid
// sequences simply through collecting user command line arguments, for
// example.
#[cfg(unix)] {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
// Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
// respectively. The value 0x80 is a lone continuation byte, invalid
// in a UTF-8 sequence.
let source = [0x66, 0x6f, 0x80, 0x6f];
let os_str = OsStr::from_bytes(&source[..]);
assert_eq!(os_str.to_string_lossy(), "fo�o");
}
#[cfg(windows)] {
use std::ffi::OsString;
use std::os::windows::prelude::*;
// Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
// respectively. The value 0xD800 is a lone surrogate half, invalid
// in a UTF-16 sequence.
let source = [0x0066, 0x006f, 0xD800, 0x006f];
let os_string = OsString::from_wide(&source[..]);
let os_str = os_string.as_os_str();
assert_eq!(os_str.to_string_lossy(), "fo�o");
}
1.0.0 · sourcepub fn to_os_string(&self) -> OsString
pub fn to_os_string(&self) -> OsString
1.9.0 · sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Checks whether the OsStr
is empty.
Examples
use std::ffi::OsStr;
let os_str = OsStr::new("");
assert!(os_str.is_empty());
let os_str = OsStr::new("foo");
assert!(!os_str.is_empty());
1.9.0 · sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the length of this OsStr
.
Note that this does not return the number of bytes in the string in OS string form.
The length returned is that of the underlying storage used by OsStr
.
As discussed in the OsString
introduction, OsString
and OsStr
store strings in a form best suited for cheap inter-conversion between
native-platform and Rust string forms, which may differ significantly
from both of them, including in storage size and encoding.
This number is simply useful for passing to other methods, like
OsString::with_capacity
to avoid reallocations.
See the main OsString
documentation information about encoding and capacity units.
Examples
use std::ffi::OsStr;
let os_str = OsStr::new("");
assert_eq!(os_str.len(), 0);
let os_str = OsStr::new("foo");
assert_eq!(os_str.len(), 3);
1.53.0 · sourcepub fn to_ascii_lowercase(&self) -> OsString
pub fn to_ascii_lowercase(&self) -> OsString
Returns a copy of this string where each character is mapped to its ASCII lower case equivalent.
ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.
To lowercase the value in-place, use OsStr::make_ascii_lowercase
.
Examples
use std::ffi::OsString;
let s = OsString::from("Grüße, Jürgen ❤");
assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
1.53.0 · sourcepub fn to_ascii_uppercase(&self) -> OsString
pub fn to_ascii_uppercase(&self) -> OsString
Returns a copy of this string where each character is mapped to its ASCII upper case equivalent.
ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.
To uppercase the value in-place, use OsStr::make_ascii_uppercase
.
Examples
use std::ffi::OsString;
let s = OsString::from("Grüße, Jürgen ❤");
assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
1.53.0 · sourcepub fn is_ascii(&self) -> bool
pub fn is_ascii(&self) -> bool
Checks if all characters in this string are within the ASCII range.
Examples
use std::ffi::OsString;
let ascii = OsString::from("hello!\n");
let non_ascii = OsString::from("Grüße, Jürgen ❤");
assert!(ascii.is_ascii());
assert!(!non_ascii.is_ascii());
1.53.0 · sourcepub fn eq_ignore_ascii_case<S>(&self, other: S) -> boolwhere
S: AsRef<OsStr>,
pub fn eq_ignore_ascii_case<S>(&self, other: S) -> boolwhere
S: AsRef<OsStr>,
Checks that two strings are an ASCII case-insensitive match.
Same as to_ascii_lowercase(a) == to_ascii_lowercase(b)
,
but without allocating and copying temporaries.
Examples
use std::ffi::OsString;
assert!(OsString::from("Ferris").eq_ignore_ascii_case("FERRIS"));
assert!(OsString::from("Ferrös").eq_ignore_ascii_case("FERRöS"));
assert!(!OsString::from("Ferrös").eq_ignore_ascii_case("FERRÖS"));
Trait Implementations§
source§impl<I: Into<OsStr>> IntoResettable<OsStr> for I
impl<I: Into<OsStr>> IntoResettable<OsStr> for I
source§fn into_resettable(self) -> Resettable<OsStr>
fn into_resettable(self) -> Resettable<OsStr>
source§impl IntoResettable<OsStr> for Option<&'static str>
impl IntoResettable<OsStr> for Option<&'static str>
source§fn into_resettable(self) -> Resettable<OsStr>
fn into_resettable(self) -> Resettable<OsStr>
source§impl Ord for OsStr
impl Ord for OsStr
source§impl PartialOrd<OsStr> for OsStr
impl PartialOrd<OsStr> for OsStr
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
operator. Read more