pub struct Str { /* private fields */ }
Expand description
A UTF-8-encoded fixed string
NOTE: To support dynamic values (i.e. String
), enable the string
feature
Implementations§
source§impl Str
impl Str
sourcepub fn as_str(&self) -> &str
pub fn as_str(&self) -> &str
Get the raw string of the Str
Examples found in repository?
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 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
pub fn as_str(&self) -> &str {
self.0.as_str()
}
pub(crate) fn as_internal_str(&self) -> &Str {
&self.0
}
}
impl From<&'_ Id> for Id {
fn from(id: &'_ Id) -> Self {
id.clone()
}
}
impl From<Str> for Id {
fn from(name: Str) -> Self {
Self(name)
}
}
impl From<&'_ Str> for Id {
fn from(name: &'_ Str) -> Self {
Self(name.into())
}
}
#[cfg(feature = "string")]
impl From<std::string::String> for Id {
fn from(name: std::string::String) -> Self {
Self(name.into())
}
}
#[cfg(feature = "string")]
impl From<&'_ std::string::String> for Id {
fn from(name: &'_ std::string::String) -> Self {
Self(name.into())
}
}
impl From<&'static str> for Id {
fn from(name: &'static str) -> Self {
Self(name.into())
}
}
impl From<&'_ &'static str> for Id {
fn from(name: &'_ &'static str) -> Self {
Self(name.into())
}
}
impl From<Id> for Str {
fn from(name: Id) -> Self {
name.0
}
}
impl From<Id> for String {
fn from(name: Id) -> Self {
Str::from(name).into()
}
}
impl std::fmt::Display for Id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.as_str(), f)
}
}
impl std::fmt::Debug for Id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self.as_str(), f)
}
}
impl AsRef<str> for Id {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl std::borrow::Borrow<str> for Id {
#[inline]
fn borrow(&self) -> &str {
self.as_str()
}
}
impl PartialEq<str> for Id {
#[inline]
fn eq(&self, other: &str) -> bool {
PartialEq::eq(self.as_str(), other)
}
}
impl PartialEq<Id> for str {
#[inline]
fn eq(&self, other: &Id) -> bool {
PartialEq::eq(self, other.as_str())
}
}
impl PartialEq<&'_ str> for Id {
#[inline]
fn eq(&self, other: &&str) -> bool {
PartialEq::eq(self.as_str(), *other)
}
}
impl PartialEq<Id> for &'_ str {
#[inline]
fn eq(&self, other: &Id) -> bool {
PartialEq::eq(*self, other.as_str())
}
}
impl PartialEq<Str> for Id {
#[inline]
fn eq(&self, other: &Str) -> bool {
PartialEq::eq(self.as_str(), other.as_str())
}
}
impl PartialEq<Id> for Str {
#[inline]
fn eq(&self, other: &Id) -> bool {
PartialEq::eq(self.as_str(), other.as_str())
}
More examples
3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125
pub fn get_name(&self) -> &str {
self.name.as_str()
}
#[inline]
#[cfg(debug_assertions)]
pub(crate) fn get_name_str(&self) -> &Str {
&self.name
}
/// Get the version of the cmd.
#[inline]
pub fn get_version(&self) -> Option<&str> {
self.version.as_deref()
}
/// Get the long version of the cmd.
#[inline]
pub fn get_long_version(&self) -> Option<&str> {
self.long_version.as_deref()
}
/// Get the authors of the cmd.
#[inline]
pub fn get_author(&self) -> Option<&str> {
self.author.as_deref()
}
/// Get the short flag of the subcommand.
#[inline]
pub fn get_short_flag(&self) -> Option<char> {
self.short_flag
}
/// Get the long flag of the subcommand.
#[inline]
pub fn get_long_flag(&self) -> Option<&str> {
self.long_flag.as_deref()
}
/// Get the help message specified via [`Command::about`].
///
/// [`Command::about`]: Command::about()
#[inline]
pub fn get_about(&self) -> Option<&StyledStr> {
self.about.as_ref()
}
/// Get the help message specified via [`Command::long_about`].
///
/// [`Command::long_about`]: Command::long_about()
#[inline]
pub fn get_long_about(&self) -> Option<&StyledStr> {
self.long_about.as_ref()
}
/// Get the custom section heading specified via [`Command::next_help_heading`].
///
/// [`Command::help_heading`]: Command::help_heading()
#[inline]
pub fn get_next_help_heading(&self) -> Option<&str> {
self.current_help_heading.as_deref()
}
/// Iterate through the *visible* aliases for this subcommand.
#[inline]
pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> + '_ {
self.aliases
.iter()
.filter(|(_, vis)| *vis)
.map(|a| a.0.as_str())
}
/// Iterate through the *visible* short aliases for this subcommand.
#[inline]
pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
self.short_flag_aliases
.iter()
.filter(|(_, vis)| *vis)
.map(|a| a.0)
}
/// Iterate through the *visible* long aliases for this subcommand.
#[inline]
pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ {
self.long_flag_aliases
.iter()
.filter(|(_, vis)| *vis)
.map(|a| a.0.as_str())
}
/// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden.
#[inline]
pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ {
self.aliases.iter().map(|a| a.0.as_str())
}
/// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden.
#[inline]
pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
self.short_flag_aliases.iter().map(|a| a.0)
}
/// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden.
#[inline]
pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ {
self.long_flag_aliases.iter().map(|a| a.0.as_str())
}
#[inline]
pub(crate) fn is_set(&self, s: AppSettings) -> bool {
self.settings.is_set(s) || self.g_settings.is_set(s)
}
/// Should we color the output?
pub fn get_color(&self) -> ColorChoice {
debug!("Command::color: Color setting...");
if cfg!(feature = "color") {
if self.is_set(AppSettings::ColorNever) {
debug!("Never");
ColorChoice::Never
} else if self.is_set(AppSettings::ColorAlways) {
debug!("Always");
ColorChoice::Always
} else {
debug!("Auto");
ColorChoice::Auto
}
} else {
ColorChoice::Never
}
}
/// Iterate through the set of subcommands, getting a reference to each.
#[inline]
pub fn get_subcommands(&self) -> impl Iterator<Item = &Command> {
self.subcommands.iter()
}
/// Iterate through the set of subcommands, getting a mutable reference to each.
#[inline]
pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut Command> {
self.subcommands.iter_mut()
}
/// Returns `true` if this `Command` has subcommands.
#[inline]
pub fn has_subcommands(&self) -> bool {
!self.subcommands.is_empty()
}
/// Returns the help heading for listing subcommands.
#[inline]
pub fn get_subcommand_help_heading(&self) -> Option<&str> {
self.subcommand_heading.as_deref()
}
/// Returns the subcommand value name.
#[inline]
pub fn get_subcommand_value_name(&self) -> Option<&str> {
self.subcommand_value_name.as_deref()
}
/// Returns the help heading for listing subcommands.
#[inline]
pub fn get_before_help(&self) -> Option<&StyledStr> {
self.before_help.as_ref()
}
/// Returns the help heading for listing subcommands.
#[inline]
pub fn get_before_long_help(&self) -> Option<&StyledStr> {
self.before_long_help.as_ref()
}
/// Returns the help heading for listing subcommands.
#[inline]
pub fn get_after_help(&self) -> Option<&StyledStr> {
self.after_help.as_ref()
}
/// Returns the help heading for listing subcommands.
#[inline]
pub fn get_after_long_help(&self) -> Option<&StyledStr> {
self.after_long_help.as_ref()
}
/// Find subcommand such that its name or one of aliases equals `name`.
///
/// This does not recurse through subcommands of subcommands.
#[inline]
pub fn find_subcommand(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command> {
let name = name.as_ref();
self.get_subcommands().find(|s| s.aliases_to(name))
}
/// Find subcommand such that its name or one of aliases equals `name`, returning
/// a mutable reference to the subcommand.
///
/// This does not recurse through subcommands of subcommands.
#[inline]
pub fn find_subcommand_mut(
&mut self,
name: impl AsRef<std::ffi::OsStr>,
) -> Option<&mut Command> {
let name = name.as_ref();
self.get_subcommands_mut().find(|s| s.aliases_to(name))
}
/// Iterate through the set of groups.
#[inline]
pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> {
self.groups.iter()
}
/// Iterate through the set of arguments.
#[inline]
pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> {
self.args.args()
}
/// Iterate through the *positionals* arguments.
#[inline]
pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> {
self.get_arguments().filter(|a| a.is_positional())
}
/// Iterate through the *options*.
pub fn get_opts(&self) -> impl Iterator<Item = &Arg> {
self.get_arguments()
.filter(|a| a.is_takes_value_set() && !a.is_positional())
}
/// Get a list of all arguments the given argument conflicts with.
///
/// If the provided argument is declared as global, the conflicts will be determined
/// based on the propagation rules of global arguments.
///
/// ### Panics
///
/// If the given arg contains a conflict with an argument that is unknown to
/// this `Command`.
pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
{
if arg.is_global_set() {
self.get_global_arg_conflicts_with(arg)
} else {
let mut result = Vec::new();
for id in arg.blacklist.iter() {
if let Some(arg) = self.find(id) {
result.push(arg);
} else if let Some(group) = self.find_group(id) {
result.extend(
self.unroll_args_in_group(&group.id)
.iter()
.map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)),
);
} else {
panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd");
}
}
result
}
}
// Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
//
// This behavior follows the propagation rules of global arguments.
// It is useful for finding conflicts for arguments declared as global.
//
// ### Panics
//
// If the given arg contains a conflict with an argument that is unknown to
// this `Command`.
fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
{
arg.blacklist
.iter()
.map(|id| {
self.args
.args()
.chain(
self.get_subcommands_containing(arg)
.iter()
.flat_map(|x| x.args.args()),
)
.find(|arg| arg.get_id() == id)
.expect(
"Command::get_arg_conflicts_with: \
The passed arg conflicts with an arg unknown to the cmd",
)
})
.collect()
}
// Get a list of subcommands which contain the provided Argument
//
// This command will only include subcommands in its list for which the subcommands
// parent also contains the Argument.
//
// This search follows the propagation rules of global arguments.
// It is useful to finding subcommands, that have inherited a global argument.
//
// **NOTE:** In this case only Sucommand_1 will be included
// Subcommand_1 (contains Arg)
// Subcommand_1.1 (doesn't contain Arg)
// Subcommand_1.1.1 (contains Arg)
//
fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> {
let mut vec = std::vec::Vec::new();
for idx in 0..self.subcommands.len() {
if self.subcommands[idx]
.args
.args()
.any(|ar| ar.get_id() == arg.get_id())
{
vec.push(&self.subcommands[idx]);
vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
}
}
vec
}
/// Report whether [`Command::no_binary_name`] is set
pub fn is_no_binary_name_set(&self) -> bool {
self.is_set(AppSettings::NoBinaryName)
}
/// Report whether [`Command::ignore_errors`] is set
pub(crate) fn is_ignore_errors_set(&self) -> bool {
self.is_set(AppSettings::IgnoreErrors)
}
/// Report whether [`Command::dont_delimit_trailing_values`] is set
pub fn is_dont_delimit_trailing_values_set(&self) -> bool {
self.is_set(AppSettings::DontDelimitTrailingValues)
}
/// Report whether [`Command::disable_version_flag`] is set
pub fn is_disable_version_flag_set(&self) -> bool {
self.is_set(AppSettings::DisableVersionFlag)
|| (self.version.is_none() && self.long_version.is_none())
}
/// Report whether [`Command::propagate_version`] is set
pub fn is_propagate_version_set(&self) -> bool {
self.is_set(AppSettings::PropagateVersion)
}
/// Report whether [`Command::next_line_help`] is set
pub fn is_next_line_help_set(&self) -> bool {
self.is_set(AppSettings::NextLineHelp)
}
/// Report whether [`Command::disable_help_flag`] is set
pub fn is_disable_help_flag_set(&self) -> bool {
self.is_set(AppSettings::DisableHelpFlag)
}
/// Report whether [`Command::disable_help_subcommand`] is set
pub fn is_disable_help_subcommand_set(&self) -> bool {
self.is_set(AppSettings::DisableHelpSubcommand)
}
/// Report whether [`Command::disable_colored_help`] is set
pub fn is_disable_colored_help_set(&self) -> bool {
self.is_set(AppSettings::DisableColoredHelp)
}
/// Report whether [`Command::help_expected`] is set
#[cfg(debug_assertions)]
pub(crate) fn is_help_expected_set(&self) -> bool {
self.is_set(AppSettings::HelpExpected)
}
#[doc(hidden)]
#[cfg_attr(
feature = "deprecated",
deprecated(since = "4.0.0", note = "This is now the default")
)]
pub fn is_dont_collapse_args_in_usage_set(&self) -> bool {
true
}
/// Report whether [`Command::infer_long_args`] is set
pub(crate) fn is_infer_long_args_set(&self) -> bool {
self.is_set(AppSettings::InferLongArgs)
}
/// Report whether [`Command::infer_subcommands`] is set
pub(crate) fn is_infer_subcommands_set(&self) -> bool {
self.is_set(AppSettings::InferSubcommands)
}
/// Report whether [`Command::arg_required_else_help`] is set
pub fn is_arg_required_else_help_set(&self) -> bool {
self.is_set(AppSettings::ArgRequiredElseHelp)
}
#[doc(hidden)]
#[cfg_attr(
feature = "deprecated",
deprecated(
since = "4.0.0",
note = "Replaced with `Arg::is_allow_hyphen_values_set`"
)
)]
pub(crate) fn is_allow_hyphen_values_set(&self) -> bool {
self.is_set(AppSettings::AllowHyphenValues)
}
#[doc(hidden)]
#[cfg_attr(
feature = "deprecated",
deprecated(
since = "4.0.0",
note = "Replaced with `Arg::is_allow_negative_numbers_set`"
)
)]
pub fn is_allow_negative_numbers_set(&self) -> bool {
self.is_set(AppSettings::AllowNegativeNumbers)
}
#[doc(hidden)]
#[cfg_attr(
feature = "deprecated",
deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`")
)]
pub fn is_trailing_var_arg_set(&self) -> bool {
self.is_set(AppSettings::TrailingVarArg)
}
/// Report whether [`Command::allow_missing_positional`] is set
pub fn is_allow_missing_positional_set(&self) -> bool {
self.is_set(AppSettings::AllowMissingPositional)
}
/// Report whether [`Command::hide`] is set
pub fn is_hide_set(&self) -> bool {
self.is_set(AppSettings::Hidden)
}
/// Report whether [`Command::subcommand_required`] is set
pub fn is_subcommand_required_set(&self) -> bool {
self.is_set(AppSettings::SubcommandRequired)
}
/// Report whether [`Command::allow_external_subcommands`] is set
pub fn is_allow_external_subcommands_set(&self) -> bool {
self.is_set(AppSettings::AllowExternalSubcommands)
}
/// Configured parser for values passed to an external subcommand
///
/// # Example
///
/// ```rust
/// let cmd = clap::Command::new("raw")
/// .external_subcommand_value_parser(clap::value_parser!(String));
/// let value_parser = cmd.get_external_subcommand_value_parser();
/// println!("{:?}", value_parser);
/// ```
pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> {
if !self.is_allow_external_subcommands_set() {
None
} else {
static DEFAULT: super::ValueParser = super::ValueParser::os_string();
Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT))
}
}
/// Report whether [`Command::args_conflicts_with_subcommands`] is set
pub fn is_args_conflicts_with_subcommands_set(&self) -> bool {
self.is_set(AppSettings::ArgsNegateSubcommands)
}
#[doc(hidden)]
pub fn is_args_override_self(&self) -> bool {
self.is_set(AppSettings::AllArgsOverrideSelf)
}
/// Report whether [`Command::subcommand_precedence_over_arg`] is set
pub fn is_subcommand_precedence_over_arg_set(&self) -> bool {
self.is_set(AppSettings::SubcommandPrecedenceOverArg)
}
/// Report whether [`Command::subcommand_negates_reqs`] is set
pub fn is_subcommand_negates_reqs_set(&self) -> bool {
self.is_set(AppSettings::SubcommandsNegateReqs)
}
/// Report whether [`Command::multicall`] is set
pub fn is_multicall_set(&self) -> bool {
self.is_set(AppSettings::Multicall)
}
}
// Internally used only
impl Command {
pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> {
self.usage_str.as_ref()
}
pub(crate) fn get_override_help(&self) -> Option<&StyledStr> {
self.help_str.as_ref()
}
#[cfg(feature = "help")]
pub(crate) fn get_help_template(&self) -> Option<&StyledStr> {
self.template.as_ref()
}
#[cfg(feature = "help")]
pub(crate) fn get_term_width(&self) -> Option<usize> {
self.term_w
}
#[cfg(feature = "help")]
pub(crate) fn get_max_term_width(&self) -> Option<usize> {
self.max_w
}
pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> {
self.replacers.get(key).map(|v| v.as_slice())
}
pub(crate) fn get_keymap(&self) -> &MKeyMap {
&self.args
}
fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) {
global_arg_vec.extend(
self.args
.args()
.filter(|a| a.is_global_set())
.map(|ga| ga.id.clone()),
);
if let Some((id, matches)) = matches.subcommand() {
if let Some(used_sub) = self.find_subcommand(id) {
used_sub.get_used_global_args(matches, global_arg_vec);
}
}
}
fn _do_parse(
&mut self,
raw_args: &mut clap_lex::RawArgs,
args_cursor: clap_lex::ArgCursor,
) -> ClapResult<ArgMatches> {
debug!("Command::_do_parse");
// If there are global arguments, or settings we need to propagate them down to subcommands
// before parsing in case we run into a subcommand
self._build_self(false);
let mut matcher = ArgMatcher::new(self);
// do the real parsing
let mut parser = Parser::new(self);
if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) {
if self.is_set(AppSettings::IgnoreErrors) {
debug!("Command::_do_parse: ignoring error: {}", error);
} else {
return Err(error);
}
}
let mut global_arg_vec = Default::default();
self.get_used_global_args(&matcher, &mut global_arg_vec);
matcher.propagate_globals(&global_arg_vec);
Ok(matcher.into_inner())
}
/// Prepare for introspecting on all included [`Command`]s
///
/// Call this on the top-level [`Command`] when done building and before reading state for
/// cases like completions, custom help output, etc.
pub fn build(&mut self) {
self._build_recursive(true);
self._build_bin_names_internal();
}
pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) {
self._build_self(expand_help_tree);
for subcmd in self.get_subcommands_mut() {
subcmd._build_recursive(expand_help_tree);
}
}
pub(crate) fn _build_self(&mut self, expand_help_tree: bool) {
debug!("Command::_build: name={:?}", self.get_name());
if !self.settings.is_set(AppSettings::Built) {
// Make sure all the globally set flags apply to us as well
self.settings = self.settings | self.g_settings;
if self.is_multicall_set() {
self.settings.insert(AppSettings::SubcommandRequired.into());
self.settings.insert(AppSettings::DisableHelpFlag.into());
self.settings.insert(AppSettings::DisableVersionFlag.into());
}
if !cfg!(feature = "help") && self.get_override_help().is_none() {
self.settings.insert(AppSettings::DisableHelpFlag.into());
self.settings
.insert(AppSettings::DisableHelpSubcommand.into());
}
if self.is_set(AppSettings::ArgsNegateSubcommands) {
self.settings
.insert(AppSettings::SubcommandsNegateReqs.into());
}
if self.external_value_parser.is_some() {
self.settings
.insert(AppSettings::AllowExternalSubcommands.into());
}
if !self.has_subcommands() {
self.settings
.insert(AppSettings::DisableHelpSubcommand.into());
}
self._propagate();
self._check_help_and_version(expand_help_tree);
self._propagate_global_args();
let mut pos_counter = 1;
let hide_pv = self.is_set(AppSettings::HidePossibleValues);
for a in self.args.args_mut() {
// Fill in the groups
for g in &a.groups {
if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
ag.args.push(a.get_id().clone());
} else {
let mut ag = ArgGroup::new(g);
ag.args.push(a.get_id().clone());
self.groups.push(ag);
}
}
// Figure out implied settings
a._build();
if hide_pv && a.is_takes_value_set() {
a.settings.set(ArgSettings::HidePossibleValues);
}
if a.is_positional() && a.index.is_none() {
a.index = Some(pos_counter);
pos_counter += 1;
}
}
self.args._build();
#[allow(deprecated)]
{
let highest_idx = self
.get_keymap()
.keys()
.filter_map(|x| {
if let crate::mkeymap::KeyType::Position(n) = x {
Some(*n)
} else {
None
}
})
.max()
.unwrap_or(0);
let is_trailing_var_arg_set = self.is_trailing_var_arg_set();
let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set();
let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set();
for arg in self.args.args_mut() {
if is_allow_hyphen_values_set && arg.is_takes_value_set() {
arg.settings.insert(ArgSettings::AllowHyphenValues.into());
}
if is_allow_negative_numbers_set && arg.is_takes_value_set() {
arg.settings
.insert(ArgSettings::AllowNegativeNumbers.into());
}
if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) {
arg.settings.insert(ArgSettings::TrailingVarArg.into());
}
}
}
#[cfg(debug_assertions)]
assert_app(self);
self.settings.set(AppSettings::Built);
} else {
debug!("Command::_build: already built");
}
}
pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
use std::fmt::Write;
let mut mid_string = String::from(" ");
#[cfg(feature = "usage")]
if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
{
let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)
for s in &reqs {
mid_string.push_str(&s.to_string());
mid_string.push(' ');
}
}
let is_multicall_set = self.is_multicall_set();
let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));
// Display subcommand name, short and long in usage
let mut sc_names = String::new();
sc_names.push_str(sc.name.as_str());
let mut flag_subcmd = false;
if let Some(l) = sc.get_long_flag() {
write!(sc_names, "|--{}", l).unwrap();
flag_subcmd = true;
}
if let Some(s) = sc.get_short_flag() {
write!(sc_names, "|-{}", s).unwrap();
flag_subcmd = true;
}
if flag_subcmd {
sc_names = format!("{{{}}}", sc_names);
}
let usage_name = self
.bin_name
.as_ref()
.map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
.unwrap_or(sc_names);
sc.usage_name = Some(usage_name);
// bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
// a space
let bin_name = format!(
"{}{}{}",
self.bin_name.as_deref().unwrap_or_default(),
if self.bin_name.is_some() { " " } else { "" },
&*sc.name
);
debug!(
"Command::_build_subcommand Setting bin_name of {} to {:?}",
sc.name, bin_name
);
sc.bin_name = Some(bin_name);
if sc.display_name.is_none() {
let self_display_name = if is_multicall_set {
self.display_name.as_deref().unwrap_or("")
} else {
self.display_name.as_deref().unwrap_or(&self.name)
};
let display_name = format!(
"{}{}{}",
self_display_name,
if !self_display_name.is_empty() {
"-"
} else {
""
},
&*sc.name
);
debug!(
"Command::_build_subcommand Setting display_name of {} to {:?}",
sc.name, display_name
);
sc.display_name = Some(display_name);
}
// Ensure all args are built and ready to parse
sc._build_self(false);
Some(sc)
}
fn _build_bin_names_internal(&mut self) {
debug!("Command::_build_bin_names");
if !self.is_set(AppSettings::BinNameBuilt) {
let mut mid_string = String::from(" ");
#[cfg(feature = "usage")]
if !self.is_subcommand_negates_reqs_set()
&& !self.is_args_conflicts_with_subcommands_set()
{
let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)
for s in &reqs {
mid_string.push_str(&s.to_string());
mid_string.push(' ');
}
}
let is_multicall_set = self.is_multicall_set();
let self_bin_name = if is_multicall_set {
self.bin_name.as_deref().unwrap_or("")
} else {
self.bin_name.as_deref().unwrap_or(&self.name)
}
.to_owned();
for mut sc in &mut self.subcommands {
debug!("Command::_build_bin_names:iter: bin_name set...");
if sc.usage_name.is_none() {
use std::fmt::Write;
// Display subcommand name, short and long in usage
let mut sc_names = String::new();
sc_names.push_str(sc.name.as_str());
let mut flag_subcmd = false;
if let Some(l) = sc.get_long_flag() {
write!(sc_names, "|--{}", l).unwrap();
flag_subcmd = true;
}
if let Some(s) = sc.get_short_flag() {
write!(sc_names, "|-{}", s).unwrap();
flag_subcmd = true;
}
if flag_subcmd {
sc_names = format!("{{{}}}", sc_names);
}
let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
debug!(
"Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
sc.name, usage_name
);
sc.usage_name = Some(usage_name);
} else {
debug!(
"Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
sc.name, sc.usage_name
);
}
if sc.bin_name.is_none() {
let bin_name = format!(
"{}{}{}",
self_bin_name,
if !self_bin_name.is_empty() { " " } else { "" },
&*sc.name
);
debug!(
"Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
sc.name, bin_name
);
sc.bin_name = Some(bin_name);
} else {
debug!(
"Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
sc.name, sc.bin_name
);
}
if sc.display_name.is_none() {
let self_display_name = if is_multicall_set {
self.display_name.as_deref().unwrap_or("")
} else {
self.display_name.as_deref().unwrap_or(&self.name)
};
let display_name = format!(
"{}{}{}",
self_display_name,
if !self_display_name.is_empty() {
"-"
} else {
""
},
&*sc.name
);
debug!(
"Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
sc.name, display_name
);
sc.display_name = Some(display_name);
} else {
debug!(
"Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
sc.name, sc.display_name
);
}
sc._build_bin_names_internal();
}
self.set(AppSettings::BinNameBuilt);
} else {
debug!("Command::_build_bin_names: already built");
}
}
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
pub fn get_name(&self) -> &str {
self.name.as_str()
}
/// Get the help specified for this argument, if any
#[inline]
pub fn get_help(&self) -> Option<&StyledStr> {
self.help.as_ref()
}
/// Get the help specified for this argument, if any and the argument
/// value is not hidden
#[inline]
#[cfg(feature = "help")]
pub(crate) fn get_visible_help(&self) -> Option<&StyledStr> {
if !self.hide {
self.get_help()
} else {
None
}
}
/// Report if [`PossibleValue::hide`] is set
#[inline]
pub fn is_hide_set(&self) -> bool {
self.hide
}
/// Report if PossibleValue is not hidden and has a help message
pub(crate) fn should_show_help(&self) -> bool {
!self.hide && self.help.is_some()
}
/// Get the name if argument value is not hidden, `None` otherwise,
/// but wrapped in quotes if it contains whitespace
#[cfg(feature = "help")]
pub(crate) fn get_visible_quoted_name(&self) -> Option<std::borrow::Cow<'_, str>> {
if !self.hide {
Some(if self.name.contains(char::is_whitespace) {
format!("{:?}", self.name).into()
} else {
self.name.as_str().into()
})
} else {
None
}
}
/// Returns all valid values of the argument value.
///
/// Namely the name and all aliases.
pub fn get_name_and_aliases(&self) -> impl Iterator<Item = &str> + '_ {
std::iter::once(self.get_name()).chain(self.aliases.iter().map(|s| s.as_str()))
}
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
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.as_str(), f)
}
}
impl std::fmt::Debug for Str {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self.as_str(), f)
}
}
impl std::ops::Deref for Str {
type Target = str;
#[inline]
fn deref(&self) -> &str {
self.as_str()
}
}
impl AsRef<str> for Str {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl AsRef<[u8]> for Str {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl AsRef<std::ffi::OsStr> for Str {
#[inline]
fn as_ref(&self) -> &std::ffi::OsStr {
(**self).as_ref()
}
}
impl AsRef<std::path::Path> for Str {
#[inline]
fn as_ref(&self) -> &std::path::Path {
std::path::Path::new(self)
}
}
impl std::borrow::Borrow<str> for Str {
#[inline]
fn borrow(&self) -> &str {
self.as_str()
}
}
impl PartialEq<str> for Str {
#[inline]
fn eq(&self, other: &str) -> bool {
PartialEq::eq(self.as_str(), other)
}
}
impl PartialEq<Str> for str {
#[inline]
fn eq(&self, other: &Str) -> bool {
PartialEq::eq(self, other.as_str())
}
}
impl PartialEq<&'_ str> for Str {
#[inline]
fn eq(&self, other: &&str) -> bool {
PartialEq::eq(self.as_str(), *other)
}
}
impl PartialEq<Str> for &'_ str {
#[inline]
fn eq(&self, other: &Str) -> bool {
PartialEq::eq(*self, other.as_str())
}
}
impl PartialEq<std::ffi::OsStr> for Str {
#[inline]
fn eq(&self, other: &std::ffi::OsStr) -> bool {
PartialEq::eq(self.as_str(), other)
}
}
impl PartialEq<Str> for std::ffi::OsStr {
#[inline]
fn eq(&self, other: &Str) -> bool {
PartialEq::eq(self, other.as_str())
}
}
impl PartialEq<&'_ std::ffi::OsStr> for Str {
#[inline]
fn eq(&self, other: &&std::ffi::OsStr) -> bool {
PartialEq::eq(self.as_str(), *other)
}
}
impl PartialEq<Str> for &'_ std::ffi::OsStr {
#[inline]
fn eq(&self, other: &Str) -> bool {
PartialEq::eq(*self, other.as_str())
}
}
impl PartialEq<std::string::String> for Str {
#[inline]
fn eq(&self, other: &std::string::String) -> bool {
PartialEq::eq(self.as_str(), other.as_str())
}
}
impl PartialEq<Str> for std::string::String {
#[inline]
fn eq(&self, other: &Str) -> bool {
PartialEq::eq(self.as_str(), other.as_str())
}
3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132
pub fn get_visible_aliases(&self) -> Option<Vec<&str>> {
if self.aliases.is_empty() {
None
} else {
Some(
self.aliases
.iter()
.filter_map(|(s, v)| if *v { Some(s.as_str()) } else { None })
.collect(),
)
}
}
/// Get *all* aliases for this argument, if any, both visible and hidden.
#[inline]
pub fn get_all_aliases(&self) -> Option<Vec<&str>> {
if self.aliases.is_empty() {
None
} else {
Some(self.aliases.iter().map(|(s, _)| s.as_str()).collect())
}
}
/// Get the long option name and its visible aliases, if any
#[inline]
pub fn get_long_and_visible_aliases(&self) -> Option<Vec<&str>> {
let mut longs = match self.get_long() {
Some(long) => vec![long],
None => return None,
};
if let Some(aliases) = self.get_visible_aliases() {
longs.extend(aliases);
}
Some(longs)
}
/// Get the names of possible values for this argument. Only useful for user
/// facing applications, such as building help messages or man files
pub fn get_possible_values(&self) -> Vec<PossibleValue> {
if !self.is_takes_value_set() {
vec![]
} else {
self.get_value_parser()
.possible_values()
.map(|pvs| pvs.collect())
.unwrap_or_default()
}
}
/// Get the names of values for this argument.
#[inline]
pub fn get_value_names(&self) -> Option<&[Str]> {
if self.val_names.is_empty() {
None
} else {
Some(&self.val_names)
}
}
/// Get the number of values for this argument.
#[inline]
pub fn get_num_args(&self) -> Option<ValueRange> {
self.num_vals
}
#[inline]
pub(crate) fn get_min_vals(&self) -> usize {
self.get_num_args().expect(INTERNAL_ERROR_MSG).min_values()
}
/// Get the delimiter between multiple values
#[inline]
pub fn get_value_delimiter(&self) -> Option<char> {
self.val_delim
}
/// Get the index of this argument, if any
#[inline]
pub fn get_index(&self) -> Option<usize> {
self.index
}
/// Get the value hint of this argument
pub fn get_value_hint(&self) -> ValueHint {
self.value_hint.unwrap_or_else(|| {
if self.is_takes_value_set() {
let type_id = self.get_value_parser().type_id();
if type_id == crate::parser::AnyValueId::of::<std::path::PathBuf>() {
ValueHint::AnyPath
} else {
ValueHint::default()
}
} else {
ValueHint::default()
}
})
}
/// Get the environment variable name specified for this argument, if any
///
/// # Examples
///
/// ```rust
/// # use std::ffi::OsStr;
/// # use clap::Arg;
/// let arg = Arg::new("foo").env("ENVIRONMENT");
/// assert_eq!(arg.get_env(), Some(OsStr::new("ENVIRONMENT")));
/// ```
#[cfg(feature = "env")]
pub fn get_env(&self) -> Option<&std::ffi::OsStr> {
self.env.as_ref().map(|x| x.0.as_os_str())
}
/// Get the default values specified for this argument, if any
///
/// # Examples
///
/// ```rust
/// # use clap::Arg;
/// let arg = Arg::new("foo").default_value("default value");
/// assert_eq!(arg.get_default_values(), &["default value"]);
/// ```
pub fn get_default_values(&self) -> &[OsStr] {
&self.default_vals
}
/// Checks whether this argument is a positional or not.
///
/// # Examples
///
/// ```
/// # use clap::Arg;
/// let arg = Arg::new("foo");
/// assert_eq!(arg.is_positional(), true);
///
/// let arg = Arg::new("foo").long("foo");
/// assert_eq!(arg.is_positional(), false);
/// ```
pub fn is_positional(&self) -> bool {
self.get_long().is_none() && self.get_short().is_none()
}
/// Reports whether [`Arg::required`] is set
pub fn is_required_set(&self) -> bool {
self.is_set(ArgSettings::Required)
}
pub(crate) fn is_multiple_values_set(&self) -> bool {
self.get_num_args().unwrap_or_default().is_multiple()
}
pub(crate) fn is_takes_value_set(&self) -> bool {
self.get_action().takes_values()
}
/// Report whether [`Arg::allow_hyphen_values`] is set
pub fn is_allow_hyphen_values_set(&self) -> bool {
self.is_set(ArgSettings::AllowHyphenValues)
}
/// Report whether [`Arg::allow_negative_numbers`] is set
pub fn is_allow_negative_numbers_set(&self) -> bool {
self.is_set(ArgSettings::AllowNegativeNumbers)
}
/// Behavior when parsing the argument
pub fn get_action(&self) -> &super::ArgAction {
const DEFAULT: super::ArgAction = super::ArgAction::Set;
self.action.as_ref().unwrap_or(&DEFAULT)
}
/// Configured parser for argument values
///
/// # Example
///
/// ```rust
/// let cmd = clap::Command::new("raw")
/// .arg(
/// clap::Arg::new("port")
/// .value_parser(clap::value_parser!(usize))
/// );
/// let value_parser = cmd.get_arguments()
/// .find(|a| a.get_id() == "port").unwrap()
/// .get_value_parser();
/// println!("{:?}", value_parser);
/// ```
pub fn get_value_parser(&self) -> &super::ValueParser {
if let Some(value_parser) = self.value_parser.as_ref() {
value_parser
} else {
static DEFAULT: super::ValueParser = super::ValueParser::string();
&DEFAULT
}
}
/// Report whether [`Arg::global`] is set
pub fn is_global_set(&self) -> bool {
self.is_set(ArgSettings::Global)
}
/// Report whether [`Arg::next_line_help`] is set
pub fn is_next_line_help_set(&self) -> bool {
self.is_set(ArgSettings::NextLineHelp)
}
/// Report whether [`Arg::hide`] is set
pub fn is_hide_set(&self) -> bool {
self.is_set(ArgSettings::Hidden)
}
/// Report whether [`Arg::hide_default_value`] is set
pub fn is_hide_default_value_set(&self) -> bool {
self.is_set(ArgSettings::HideDefaultValue)
}
/// Report whether [`Arg::hide_possible_values`] is set
pub fn is_hide_possible_values_set(&self) -> bool {
self.is_set(ArgSettings::HidePossibleValues)
}
/// Report whether [`Arg::hide_env`] is set
#[cfg(feature = "env")]
pub fn is_hide_env_set(&self) -> bool {
self.is_set(ArgSettings::HideEnv)
}
/// Report whether [`Arg::hide_env_values`] is set
#[cfg(feature = "env")]
pub fn is_hide_env_values_set(&self) -> bool {
self.is_set(ArgSettings::HideEnvValues)
}
/// Report whether [`Arg::hide_short_help`] is set
pub fn is_hide_short_help_set(&self) -> bool {
self.is_set(ArgSettings::HiddenShortHelp)
}
/// Report whether [`Arg::hide_long_help`] is set
pub fn is_hide_long_help_set(&self) -> bool {
self.is_set(ArgSettings::HiddenLongHelp)
}
/// Report whether [`Arg::require_equals`] is set
pub fn is_require_equals_set(&self) -> bool {
self.is_set(ArgSettings::RequireEquals)
}
/// Reports whether [`Arg::exclusive`] is set
pub fn is_exclusive_set(&self) -> bool {
self.is_set(ArgSettings::Exclusive)
}
/// Report whether [`Arg::trailing_var_arg`] is set
pub fn is_trailing_var_arg_set(&self) -> bool {
self.is_set(ArgSettings::TrailingVarArg)
}
/// Reports whether [`Arg::last`] is set
pub fn is_last_set(&self) -> bool {
self.is_set(ArgSettings::Last)
}
/// Reports whether [`Arg::ignore_case`] is set
pub fn is_ignore_case_set(&self) -> bool {
self.is_set(ArgSettings::IgnoreCase)
}
}
/// # Internally used only
impl Arg {
pub(crate) fn _build(&mut self) {
if self.action.is_none() {
if self.num_vals == Some(ValueRange::EMPTY) {
let action = super::ArgAction::SetTrue;
self.action = Some(action);
} else {
let action =
if self.is_positional() && self.num_vals.unwrap_or_default().is_unbounded() {
// Allow collecting arguments interleaved with flags
//
// Bounded values are probably a group and the user should explicitly opt-in to
// Append
super::ArgAction::Append
} else {
super::ArgAction::Set
};
self.action = Some(action);
}
}
if let Some(action) = self.action.as_ref() {
if let Some(default_value) = action.default_value() {
if self.default_vals.is_empty() {
self.default_vals = vec![default_value.into()];
}
}
if let Some(default_value) = action.default_missing_value() {
if self.default_missing_vals.is_empty() {
self.default_missing_vals = vec![default_value.into()];
}
}
}
if self.value_parser.is_none() {
if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) {
self.value_parser = Some(default);
} else {
self.value_parser = Some(super::ValueParser::string());
}
}
let val_names_len = self.val_names.len();
if val_names_len > 1 {
self.num_vals.get_or_insert(val_names_len.into());
} else {
let nargs = if self.get_action().takes_values() {
ValueRange::SINGLE
} else {
ValueRange::EMPTY
};
self.num_vals.get_or_insert(nargs);
}
}
// Used for positionals when printing
pub(crate) fn name_no_brackets(&self) -> String {
debug!("Arg::name_no_brackets:{}", self.get_id());
let delim = " ";
if !self.val_names.is_empty() {
debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names);
if self.val_names.len() > 1 {
self.val_names
.iter()
.map(|n| format!("<{}>", n))
.collect::<Vec<_>>()
.join(delim)
} else {
self.val_names
.first()
.expect(INTERNAL_ERROR_MSG)
.as_str()
.to_owned()
}
} else {
debug!("Arg::name_no_brackets: just name");
self.get_id().as_str().to_owned()
}
}
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
fn spec_vals(&self, a: &Arg) -> String {
debug!("HelpTemplate::spec_vals: a={}", a);
let mut spec_vals = Vec::new();
#[cfg(feature = "env")]
if let Some(ref env) = a.env {
if !a.is_hide_env_set() {
debug!(
"HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]",
env.0, env.1
);
let env_val = if !a.is_hide_env_values_set() {
format!(
"={}",
env.1
.as_ref()
.map(|s| s.to_string_lossy())
.unwrap_or_default()
)
} else {
Default::default()
};
let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val);
spec_vals.push(env_info);
}
}
if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
debug!(
"HelpTemplate::spec_vals: Found default value...[{:?}]",
a.default_vals
);
let pvs = a
.default_vals
.iter()
.map(|pvs| pvs.to_string_lossy())
.map(|pvs| {
if pvs.contains(char::is_whitespace) {
Cow::from(format!("{:?}", pvs))
} else {
pvs
}
})
.collect::<Vec<_>>()
.join(" ");
spec_vals.push(format!("[default: {}]", pvs));
}
let als = a
.aliases
.iter()
.filter(|&als| als.1) // visible
.map(|als| als.0.as_str()) // name
.collect::<Vec<_>>()
.join(", ");
if !als.is_empty() {
debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases);
spec_vals.push(format!("[aliases: {}]", als));
}
let als = a
.short_aliases
.iter()
.filter(|&als| als.1) // visible
.map(|&als| als.0.to_string()) // name
.collect::<Vec<_>>()
.join(", ");
if !als.is_empty() {
debug!(
"HelpTemplate::spec_vals: Found short aliases...{:?}",
a.short_aliases
);
spec_vals.push(format!("[short aliases: {}]", als));
}
let possible_vals = a.get_possible_values();
if !(a.is_hide_possible_values_set()
|| possible_vals.is_empty()
|| self.use_long && possible_vals.iter().any(PossibleValue::should_show_help))
{
debug!(
"HelpTemplate::spec_vals: Found possible vals...{:?}",
possible_vals
);
let pvs = possible_vals
.iter()
.filter_map(PossibleValue::get_visible_quoted_name)
.collect::<Vec<_>>()
.join(", ");
spec_vals.push(format!("[possible values: {}]", pvs));
}
let connector = if self.use_long { "\n" } else { " " };
spec_vals.join(connector)
}
Methods from Deref<Target = str>§
1.0.0 · sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the length of self
.
This length is in bytes, not char
s or graphemes. In other words,
it might not be what a human considers the length of the string.
Examples
Basic usage:
let len = "foo".len();
assert_eq!(3, len);
assert_eq!("ƒoo".len(), 4); // fancy f!
assert_eq!("ƒoo".chars().count(), 3);
1.0.0 · sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if self
has a length of zero bytes.
Examples
Basic usage:
let s = "";
assert!(s.is_empty());
let s = "not empty";
assert!(!s.is_empty());
1.9.0 · sourcepub fn is_char_boundary(&self, index: usize) -> bool
pub fn is_char_boundary(&self, index: usize) -> bool
Checks that index
-th byte is the first byte in a UTF-8 code point
sequence or the end of the string.
The start and end of the string (when index == self.len()
) are
considered to be boundaries.
Returns false
if index
is greater than self.len()
.
Examples
let s = "Löwe 老虎 Léopard";
assert!(s.is_char_boundary(0));
// start of `老`
assert!(s.is_char_boundary(6));
assert!(s.is_char_boundary(s.len()));
// second byte of `ö`
assert!(!s.is_char_boundary(2));
// third byte of `老`
assert!(!s.is_char_boundary(8));
sourcepub fn floor_char_boundary(&self, index: usize) -> usize
🔬This is a nightly-only experimental API. (round_char_boundary
)
pub fn floor_char_boundary(&self, index: usize) -> usize
round_char_boundary
)Finds the closest x
not exceeding index
where is_char_boundary(x)
is true
.
This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t exceed a given number of bytes. Note that this is done purely at the character level and can still visually split graphemes, even though the underlying characters aren’t split. For example, the emoji 🧑🔬 (scientist) could be split so that the string only includes 🧑 (person) instead.
Examples
#![feature(round_char_boundary)]
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));
let closest = s.floor_char_boundary(13);
assert_eq!(closest, 10);
assert_eq!(&s[..closest], "❤️🧡");
sourcepub fn ceil_char_boundary(&self, index: usize) -> usize
🔬This is a nightly-only experimental API. (round_char_boundary
)
pub fn ceil_char_boundary(&self, index: usize) -> usize
round_char_boundary
)Finds the closest x
not below index
where is_char_boundary(x)
is true
.
This method is the natural complement to floor_char_boundary
. See that method
for more details.
Panics
Panics if index > self.len()
.
Examples
#![feature(round_char_boundary)]
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));
let closest = s.ceil_char_boundary(13);
assert_eq!(closest, 14);
assert_eq!(&s[..closest], "❤️🧡💛");
1.0.0 · sourcepub fn as_ptr(&self) -> *const u8
pub fn as_ptr(&self) -> *const u8
Converts a string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to a
u8
. This pointer will be pointing to the first byte of the string
slice.
The caller must ensure that the returned pointer is never written to.
If you need to mutate the contents of the string slice, use as_mut_ptr
.
Examples
Basic usage:
let s = "Hello";
let ptr = s.as_ptr();
1.20.0 · sourcepub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>where
I: SliceIndex<str>,
pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>where
I: SliceIndex<str>,
Returns a subslice of str
.
This is the non-panicking alternative to indexing the str
. Returns
None
whenever equivalent indexing operation would panic.
Examples
let v = String::from("🗻∈🌏");
assert_eq!(Some("🗻"), v.get(0..4));
// indices not on UTF-8 sequence boundaries
assert!(v.get(1..).is_none());
assert!(v.get(..8).is_none());
// out of bounds
assert!(v.get(..42).is_none());
1.20.0 · sourcepub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Outputwhere
I: SliceIndex<str>,
pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Outputwhere
I: SliceIndex<str>,
Returns an unchecked subslice of str
.
This is the unchecked alternative to indexing the str
.
Safety
Callers of this function are responsible that these preconditions are satisfied:
- The starting index must not exceed the ending index;
- Indexes must be within bounds of the original slice;
- Indexes must lie on UTF-8 sequence boundaries.
Failing that, the returned string slice may reference invalid memory or
violate the invariants communicated by the str
type.
Examples
let v = "🗻∈🌏";
unsafe {
assert_eq!("🗻", v.get_unchecked(0..4));
assert_eq!("∈", v.get_unchecked(4..7));
assert_eq!("🌏", v.get_unchecked(7..11));
}
1.0.0 · sourcepub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str
👎Deprecated since 1.29.0: use get_unchecked(begin..end)
instead
pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str
get_unchecked(begin..end)
insteadCreates a string slice from another string slice, bypassing safety checks.
This is generally not recommended, use with caution! For a safe
alternative see str
and Index
.
This new slice goes from begin
to end
, including begin
but
excluding end
.
To get a mutable string slice instead, see the
slice_mut_unchecked
method.
Safety
Callers of this function are responsible that three preconditions are satisfied:
begin
must not exceedend
.begin
andend
must be byte positions within the string slice.begin
andend
must lie on UTF-8 sequence boundaries.
Examples
Basic usage:
let s = "Löwe 老虎 Léopard";
unsafe {
assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
}
let s = "Hello, world!";
unsafe {
assert_eq!("world", s.slice_unchecked(7, 12));
}
1.4.0 · sourcepub fn split_at(&self, mid: usize) -> (&str, &str)
pub fn split_at(&self, mid: usize) -> (&str, &str)
Divide one string slice into two at an index.
The argument, mid
, should be a byte offset from the start of the
string. It must also be on the boundary of a UTF-8 code point.
The two slices returned go from the start of the string slice to mid
,
and from mid
to the end of the string slice.
To get mutable string slices instead, see the split_at_mut
method.
Panics
Panics if mid
is not on a UTF-8 code point boundary, or if it is
past the end of the last code point of the string slice.
Examples
Basic usage:
let s = "Per Martin-Löf";
let (first, last) = s.split_at(3);
assert_eq!("Per", first);
assert_eq!(" Martin-Löf", last);
1.0.0 · sourcepub fn chars(&self) -> Chars<'_>
pub fn chars(&self) -> Chars<'_>
Returns an iterator over the char
s of a string slice.
As a string slice consists of valid UTF-8, we can iterate through a
string slice by char
. This method returns such an iterator.
It’s important to remember that char
represents a Unicode Scalar
Value, and might not match your idea of what a ‘character’ is. Iteration
over grapheme clusters may be what you actually want. This functionality
is not provided by Rust’s standard library, check crates.io instead.
Examples
Basic usage:
let word = "goodbye";
let count = word.chars().count();
assert_eq!(7, count);
let mut chars = word.chars();
assert_eq!(Some('g'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('d'), chars.next());
assert_eq!(Some('b'), chars.next());
assert_eq!(Some('y'), chars.next());
assert_eq!(Some('e'), chars.next());
assert_eq!(None, chars.next());
Remember, char
s might not match your intuition about characters:
let y = "y̆";
let mut chars = y.chars();
assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());
assert_eq!(None, chars.next());
1.0.0 · sourcepub fn char_indices(&self) -> CharIndices<'_>
pub fn char_indices(&self) -> CharIndices<'_>
Returns an iterator over the char
s of a string slice, and their
positions.
As a string slice consists of valid UTF-8, we can iterate through a
string slice by char
. This method returns an iterator of both
these char
s, as well as their byte positions.
The iterator yields tuples. The position is first, the char
is
second.
Examples
Basic usage:
let word = "goodbye";
let count = word.char_indices().count();
assert_eq!(7, count);
let mut char_indices = word.char_indices();
assert_eq!(Some((0, 'g')), char_indices.next());
assert_eq!(Some((1, 'o')), char_indices.next());
assert_eq!(Some((2, 'o')), char_indices.next());
assert_eq!(Some((3, 'd')), char_indices.next());
assert_eq!(Some((4, 'b')), char_indices.next());
assert_eq!(Some((5, 'y')), char_indices.next());
assert_eq!(Some((6, 'e')), char_indices.next());
assert_eq!(None, char_indices.next());
Remember, char
s might not match your intuition about characters:
let yes = "y̆es";
let mut char_indices = yes.char_indices();
assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
assert_eq!(Some((1, '\u{0306}')), char_indices.next());
// note the 3 here - the last character took up two bytes
assert_eq!(Some((3, 'e')), char_indices.next());
assert_eq!(Some((4, 's')), char_indices.next());
assert_eq!(None, char_indices.next());
1.0.0 · sourcepub fn bytes(&self) -> Bytes<'_>
pub fn bytes(&self) -> Bytes<'_>
An iterator over the bytes of a string slice.
As a string slice consists of a sequence of bytes, we can iterate through a string slice by byte. This method returns such an iterator.
Examples
Basic usage:
let mut bytes = "bors".bytes();
assert_eq!(Some(b'b'), bytes.next());
assert_eq!(Some(b'o'), bytes.next());
assert_eq!(Some(b'r'), bytes.next());
assert_eq!(Some(b's'), bytes.next());
assert_eq!(None, bytes.next());
1.1.0 · sourcepub fn split_whitespace(&self) -> SplitWhitespace<'_>
pub fn split_whitespace(&self) -> SplitWhitespace<'_>
Splits a string slice by whitespace.
The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of whitespace.
‘Whitespace’ is defined according to the terms of the Unicode Derived
Core Property White_Space
. If you only want to split on ASCII whitespace
instead, use split_ascii_whitespace
.
Examples
Basic usage:
let mut iter = "A few words".split_whitespace();
assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());
assert_eq!(None, iter.next());
All kinds of whitespace are considered:
let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());
assert_eq!(None, iter.next());
If the string is empty or all whitespace, the iterator yields no string slices:
assert_eq!("".split_whitespace().next(), None);
assert_eq!(" ".split_whitespace().next(), None);
1.34.0 · sourcepub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_>
pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_>
Splits a string slice by ASCII whitespace.
The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of ASCII whitespace.
To split by Unicode Whitespace
instead, use split_whitespace
.
Examples
Basic usage:
let mut iter = "A few words".split_ascii_whitespace();
assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());
assert_eq!(None, iter.next());
All kinds of ASCII whitespace are considered:
let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());
assert_eq!(None, iter.next());
If the string is empty or all ASCII whitespace, the iterator yields no string slices:
assert_eq!("".split_ascii_whitespace().next(), None);
assert_eq!(" ".split_ascii_whitespace().next(), None);
1.0.0 · sourcepub fn lines(&self) -> Lines<'_>
pub fn lines(&self) -> Lines<'_>
An iterator over the lines of a string, as string slices.
Lines are ended with either a newline (\n
) or a carriage return with
a line feed (\r\n
).
The final line ending is optional. A string that ends with a final line ending will return the same lines as an otherwise identical string without a final line ending.
Examples
Basic usage:
let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();
assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());
assert_eq!(None, lines.next());
The final line ending isn’t required:
let text = "foo\nbar\n\r\nbaz";
let mut lines = text.lines();
assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());
assert_eq!(None, lines.next());
1.0.0 · sourcepub fn lines_any(&self) -> LinesAny<'_>
👎Deprecated since 1.4.0: use lines() instead now
pub fn lines_any(&self) -> LinesAny<'_>
An iterator over the lines of a string.
1.8.0 · sourcepub fn encode_utf16(&self) -> EncodeUtf16<'_>
pub fn encode_utf16(&self) -> EncodeUtf16<'_>
Returns an iterator of u16
over the string encoded as UTF-16.
Examples
Basic usage:
let text = "Zażółć gęślą jaźń";
let utf8_len = text.len();
let utf16_len = text.encode_utf16().count();
assert!(utf16_len <= utf8_len);
1.0.0 · sourcepub fn contains<'a, P>(&'a self, pat: P) -> boolwhere
P: Pattern<'a>,
pub fn contains<'a, P>(&'a self, pat: P) -> boolwhere
P: Pattern<'a>,
Returns true
if the given pattern matches a sub-slice of
this string slice.
Returns false
if it does not.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Examples
Basic usage:
let bananas = "bananas";
assert!(bananas.contains("nana"));
assert!(!bananas.contains("apples"));
1.0.0 · sourcepub fn starts_with<'a, P>(&'a self, pat: P) -> boolwhere
P: Pattern<'a>,
pub fn starts_with<'a, P>(&'a self, pat: P) -> boolwhere
P: Pattern<'a>,
Returns true
if the given pattern matches a prefix of this
string slice.
Returns false
if it does not.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Examples
Basic usage:
let bananas = "bananas";
assert!(bananas.starts_with("bana"));
assert!(!bananas.starts_with("nana"));
1.0.0 · sourcepub fn ends_with<'a, P>(&'a self, pat: P) -> boolwhere
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn ends_with<'a, P>(&'a self, pat: P) -> boolwhere
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
Returns true
if the given pattern matches a suffix of this
string slice.
Returns false
if it does not.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Examples
Basic usage:
let bananas = "bananas";
assert!(bananas.ends_with("anas"));
assert!(!bananas.ends_with("nana"));
1.0.0 · sourcepub fn find<'a, P>(&'a self, pat: P) -> Option<usize>where
P: Pattern<'a>,
pub fn find<'a, P>(&'a self, pat: P) -> Option<usize>where
P: Pattern<'a>,
Returns the byte index of the first character of this string slice that matches the pattern.
Returns None
if the pattern doesn’t match.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Examples
Simple patterns:
let s = "Löwe 老虎 Léopard Gepardi";
assert_eq!(s.find('L'), Some(0));
assert_eq!(s.find('é'), Some(14));
assert_eq!(s.find("pard"), Some(17));
More complex patterns using point-free style and closures:
let s = "Löwe 老虎 Léopard";
assert_eq!(s.find(char::is_whitespace), Some(5));
assert_eq!(s.find(char::is_lowercase), Some(1));
assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
Not finding the pattern:
let s = "Löwe 老虎 Léopard";
let x: &[_] = &['1', '2'];
assert_eq!(s.find(x), None);
1.0.0 · sourcepub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
Returns the byte index for the first character of the last match of the pattern in this string slice.
Returns None
if the pattern doesn’t match.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Examples
Simple patterns:
let s = "Löwe 老虎 Léopard Gepardi";
assert_eq!(s.rfind('L'), Some(13));
assert_eq!(s.rfind('é'), Some(14));
assert_eq!(s.rfind("pard"), Some(24));
More complex patterns with closures:
let s = "Löwe 老虎 Léopard";
assert_eq!(s.rfind(char::is_whitespace), Some(12));
assert_eq!(s.rfind(char::is_lowercase), Some(20));
Not finding the pattern:
let s = "Löwe 老虎 Léopard";
let x: &[_] = &['1', '2'];
assert_eq!(s.rfind(x), None);
1.0.0 · sourcepub fn split<'a, P>(&'a self, pat: P) -> Split<'a, P>where
P: Pattern<'a>,
pub fn split<'a, P>(&'a self, pat: P) -> Split<'a, P>where
P: Pattern<'a>,
An iterator over substrings of this string slice, separated by characters matched by a pattern.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Iterator behavior
The returned iterator will be a DoubleEndedIterator
if the pattern
allows a reverse search and forward/reverse search yields the same
elements. This is true for, e.g., char
, but not for &str
.
If the pattern allows a reverse search but its results might differ
from a forward search, the rsplit
method can be used.
Examples
Simple patterns:
let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
let v: Vec<&str> = "".split('X').collect();
assert_eq!(v, [""]);
let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
assert_eq!(v, ["lion", "", "tiger", "leopard"]);
let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);
let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
assert_eq!(v, ["abc", "def", "ghi"]);
let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);
If the pattern is a slice of chars, split on each occurrence of any of the characters:
let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
assert_eq!(v, ["2020", "11", "03", "23", "59"]);
A more complex pattern, using a closure:
let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "def", "ghi"]);
If a string contains multiple contiguous separators, you will end up with empty strings in the output:
let x = "||||a||b|c".to_string();
let d: Vec<_> = x.split('|').collect();
assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
Contiguous separators are separated by the empty string.
let x = "(///)".to_string();
let d: Vec<_> = x.split('/').collect();
assert_eq!(d, &["(", "", "", ")"]);
Separators at the start or end of a string are neighbored by empty strings.
let d: Vec<_> = "010".split("0").collect();
assert_eq!(d, &["", "1", ""]);
When the empty string is used as a separator, it separates every character in the string, along with the beginning and end of the string.
let f: Vec<_> = "rust".split("").collect();
assert_eq!(f, &["", "r", "u", "s", "t", ""]);
Contiguous separators can lead to possibly surprising behavior when whitespace is used as the separator. This code is correct:
let x = " a b c".to_string();
let d: Vec<_> = x.split(' ').collect();
assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
It does not give you:
assert_eq!(d, &["a", "b", "c"]);
Use split_whitespace
for this behavior.
1.51.0 · sourcepub fn split_inclusive<'a, P>(&'a self, pat: P) -> SplitInclusive<'a, P>where
P: Pattern<'a>,
pub fn split_inclusive<'a, P>(&'a self, pat: P) -> SplitInclusive<'a, P>where
P: Pattern<'a>,
An iterator over substrings of this string slice, separated by
characters matched by a pattern. Differs from the iterator produced by
split
in that split_inclusive
leaves the matched part as the
terminator of the substring.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Examples
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
.split_inclusive('\n').collect();
assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
If the last element of the string is matched, that element will be considered the terminator of the preceding substring. That substring will be the last item returned by the iterator.
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
.split_inclusive('\n').collect();
assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1.0.0 · sourcepub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
An iterator over substrings of the given string slice, separated by characters matched by a pattern and yielded in reverse order.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Iterator behavior
The returned iterator requires that the pattern supports a reverse
search, and it will be a DoubleEndedIterator
if a forward/reverse
search yields the same elements.
For iterating from the front, the split
method can be used.
Examples
Simple patterns:
let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
let v: Vec<&str> = "".rsplit('X').collect();
assert_eq!(v, [""]);
let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
assert_eq!(v, ["leopard", "tiger", "", "lion"]);
let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
assert_eq!(v, ["leopard", "tiger", "lion"]);
A more complex pattern, using a closure:
let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "def", "abc"]);
1.0.0 · sourcepub fn split_terminator<'a, P>(&'a self, pat: P) -> SplitTerminator<'a, P>where
P: Pattern<'a>,
pub fn split_terminator<'a, P>(&'a self, pat: P) -> SplitTerminator<'a, P>where
P: Pattern<'a>,
An iterator over substrings of the given string slice, separated by characters matched by a pattern.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Equivalent to split
, except that the trailing substring
is skipped if empty.
This method can be used for string data that is terminated, rather than separated by a pattern.
Iterator behavior
The returned iterator will be a DoubleEndedIterator
if the pattern
allows a reverse search and forward/reverse search yields the same
elements. This is true for, e.g., char
, but not for &str
.
If the pattern allows a reverse search but its results might differ
from a forward search, the rsplit_terminator
method can be used.
Examples
Basic usage:
let v: Vec<&str> = "A.B.".split_terminator('.').collect();
assert_eq!(v, ["A", "B"]);
let v: Vec<&str> = "A..B..".split_terminator(".").collect();
assert_eq!(v, ["A", "", "B", ""]);
let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
assert_eq!(v, ["A", "B", "C", "D"]);
1.0.0 · sourcepub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
An iterator over substrings of self
, separated by characters
matched by a pattern and yielded in reverse order.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Equivalent to split
, except that the trailing substring is
skipped if empty.
This method can be used for string data that is terminated, rather than separated by a pattern.
Iterator behavior
The returned iterator requires that the pattern supports a reverse search, and it will be double ended if a forward/reverse search yields the same elements.
For iterating from the front, the split_terminator
method can be
used.
Examples
let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
assert_eq!(v, ["B", "A"]);
let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
assert_eq!(v, ["", "B", "", "A"]);
let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
assert_eq!(v, ["D", "C", "B", "A"]);
1.0.0 · sourcepub fn splitn<'a, P>(&'a self, n: usize, pat: P) -> SplitN<'a, P>where
P: Pattern<'a>,
pub fn splitn<'a, P>(&'a self, n: usize, pat: P) -> SplitN<'a, P>where
P: Pattern<'a>,
An iterator over substrings of the given string slice, separated by a
pattern, restricted to returning at most n
items.
If n
substrings are returned, the last substring (the n
th substring)
will contain the remainder of the string.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Iterator behavior
The returned iterator will not be double ended, because it is not efficient to support.
If the pattern allows a reverse search, the rsplitn
method can be
used.
Examples
Simple patterns:
let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
assert_eq!(v, ["Mary", "had", "a little lambda"]);
let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
assert_eq!(v, ["lion", "", "tigerXleopard"]);
let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
assert_eq!(v, ["abcXdef"]);
let v: Vec<&str> = "".splitn(1, 'X').collect();
assert_eq!(v, [""]);
A more complex pattern, using a closure:
let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "defXghi"]);
1.0.0 · sourcepub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
An iterator over substrings of this string slice, separated by a
pattern, starting from the end of the string, restricted to returning
at most n
items.
If n
substrings are returned, the last substring (the n
th substring)
will contain the remainder of the string.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Iterator behavior
The returned iterator will not be double ended, because it is not efficient to support.
For splitting from the front, the splitn
method can be used.
Examples
Simple patterns:
let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
assert_eq!(v, ["lamb", "little", "Mary had a"]);
let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
assert_eq!(v, ["leopard", "tiger", "lionX"]);
let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
assert_eq!(v, ["leopard", "lion::tiger"]);
A more complex pattern, using a closure:
let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "abc1def"]);
1.52.0 · sourcepub fn split_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where
P: Pattern<'a>,
pub fn split_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where
P: Pattern<'a>,
Splits the string on the first occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.
Examples
assert_eq!("cfg".split_once('='), None);
assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1.52.0 · sourcepub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
Splits the string on the last occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.
Examples
assert_eq!("cfg".rsplit_once('='), None);
assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1.2.0 · sourcepub fn matches<'a, P>(&'a self, pat: P) -> Matches<'a, P>where
P: Pattern<'a>,
pub fn matches<'a, P>(&'a self, pat: P) -> Matches<'a, P>where
P: Pattern<'a>,
An iterator over the disjoint matches of a pattern within the given string slice.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Iterator behavior
The returned iterator will be a DoubleEndedIterator
if the pattern
allows a reverse search and forward/reverse search yields the same
elements. This is true for, e.g., char
, but not for &str
.
If the pattern allows a reverse search but its results might differ
from a forward search, the rmatches
method can be used.
Examples
Basic usage:
let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
assert_eq!(v, ["abc", "abc", "abc"]);
let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
assert_eq!(v, ["1", "2", "3"]);
1.2.0 · sourcepub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
An iterator over the disjoint matches of a pattern within this string slice, yielded in reverse order.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Iterator behavior
The returned iterator requires that the pattern supports a reverse
search, and it will be a DoubleEndedIterator
if a forward/reverse
search yields the same elements.
For iterating from the front, the matches
method can be used.
Examples
Basic usage:
let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
assert_eq!(v, ["abc", "abc", "abc"]);
let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
assert_eq!(v, ["3", "2", "1"]);
1.5.0 · sourcepub fn match_indices<'a, P>(&'a self, pat: P) -> MatchIndices<'a, P>where
P: Pattern<'a>,
pub fn match_indices<'a, P>(&'a self, pat: P) -> MatchIndices<'a, P>where
P: Pattern<'a>,
An iterator over the disjoint matches of a pattern within this string slice as well as the index that the match starts at.
For matches of pat
within self
that overlap, only the indices
corresponding to the first match are returned.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Iterator behavior
The returned iterator will be a DoubleEndedIterator
if the pattern
allows a reverse search and forward/reverse search yields the same
elements. This is true for, e.g., char
, but not for &str
.
If the pattern allows a reverse search but its results might differ
from a forward search, the rmatch_indices
method can be used.
Examples
Basic usage:
let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
assert_eq!(v, [(1, "abc"), (4, "abc")]);
let v: Vec<_> = "ababa".match_indices("aba").collect();
assert_eq!(v, [(0, "aba")]); // only the first `aba`
1.5.0 · sourcepub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
An iterator over the disjoint matches of a pattern within self
,
yielded in reverse order along with the index of the match.
For matches of pat
within self
that overlap, only the indices
corresponding to the last match are returned.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Iterator behavior
The returned iterator requires that the pattern supports a reverse
search, and it will be a DoubleEndedIterator
if a forward/reverse
search yields the same elements.
For iterating from the front, the match_indices
method can be used.
Examples
Basic usage:
let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
assert_eq!(v, [(4, "abc"), (1, "abc")]);
let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
assert_eq!(v, [(2, "aba")]); // only the last `aba`
1.0.0 · sourcepub fn trim(&self) -> &str
pub fn trim(&self) -> &str
Returns a string slice with leading and trailing whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode Derived
Core Property White_Space
, which includes newlines.
Examples
Basic usage:
let s = "\n Hello\tworld\t\n";
assert_eq!("Hello\tworld", s.trim());
1.30.0 · sourcepub fn trim_start(&self) -> &str
pub fn trim_start(&self) -> &str
Returns a string slice with leading whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode Derived
Core Property White_Space
, which includes newlines.
Text directionality
A string is a sequence of bytes. start
in this context means the first
position of that byte string; for a left-to-right language like English or
Russian, this will be left side, and for right-to-left languages like
Arabic or Hebrew, this will be the right side.
Examples
Basic usage:
let s = "\n Hello\tworld\t\n";
assert_eq!("Hello\tworld\t\n", s.trim_start());
Directionality:
let s = " English ";
assert!(Some('E') == s.trim_start().chars().next());
let s = " עברית ";
assert!(Some('ע') == s.trim_start().chars().next());
1.30.0 · sourcepub fn trim_end(&self) -> &str
pub fn trim_end(&self) -> &str
Returns a string slice with trailing whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode Derived
Core Property White_Space
, which includes newlines.
Text directionality
A string is a sequence of bytes. end
in this context means the last
position of that byte string; for a left-to-right language like English or
Russian, this will be right side, and for right-to-left languages like
Arabic or Hebrew, this will be the left side.
Examples
Basic usage:
let s = "\n Hello\tworld\t\n";
assert_eq!("\n Hello\tworld", s.trim_end());
Directionality:
let s = " English ";
assert!(Some('h') == s.trim_end().chars().rev().next());
let s = " עברית ";
assert!(Some('ת') == s.trim_end().chars().rev().next());
1.0.0 · sourcepub fn trim_left(&self) -> &str
👎Deprecated since 1.33.0: superseded by trim_start
pub fn trim_left(&self) -> &str
trim_start
Returns a string slice with leading whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode Derived
Core Property White_Space
.
Text directionality
A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the right side, not the left.
Examples
Basic usage:
let s = " Hello\tworld\t";
assert_eq!("Hello\tworld\t", s.trim_left());
Directionality:
let s = " English";
assert!(Some('E') == s.trim_left().chars().next());
let s = " עברית";
assert!(Some('ע') == s.trim_left().chars().next());
1.0.0 · sourcepub fn trim_right(&self) -> &str
👎Deprecated since 1.33.0: superseded by trim_end
pub fn trim_right(&self) -> &str
trim_end
Returns a string slice with trailing whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode Derived
Core Property White_Space
.
Text directionality
A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the left side, not the right.
Examples
Basic usage:
let s = " Hello\tworld\t";
assert_eq!(" Hello\tworld", s.trim_right());
Directionality:
let s = "English ";
assert!(Some('h') == s.trim_right().chars().rev().next());
let s = "עברית ";
assert!(Some('ת') == s.trim_right().chars().rev().next());
1.0.0 · sourcepub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a strwhere
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,
pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a strwhere
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,
Returns a string slice with all prefixes and suffixes that match a pattern repeatedly removed.
The pattern can be a char
, a slice of char
s, or a function
or closure that determines if a character matches.
Examples
Simple patterns:
assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
A more complex pattern, using a closure:
assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1.30.0 · sourcepub fn trim_start_matches<'a, P>(&'a self, pat: P) -> &'a strwhere
P: Pattern<'a>,
pub fn trim_start_matches<'a, P>(&'a self, pat: P) -> &'a strwhere
P: Pattern<'a>,
Returns a string slice with all prefixes that match a pattern repeatedly removed.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Text directionality
A string is a sequence of bytes. start
in this context means the first
position of that byte string; for a left-to-right language like English or
Russian, this will be left side, and for right-to-left languages like
Arabic or Hebrew, this will be the right side.
Examples
Basic usage:
assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
1.45.0 · sourcepub fn strip_prefix<'a, P>(&'a self, prefix: P) -> Option<&'a str>where
P: Pattern<'a>,
pub fn strip_prefix<'a, P>(&'a self, prefix: P) -> Option<&'a str>where
P: Pattern<'a>,
Returns a string slice with the prefix removed.
If the string starts with the pattern prefix
, returns substring after the prefix, wrapped
in Some
. Unlike trim_start_matches
, this method removes the prefix exactly once.
If the string does not start with prefix
, returns None
.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Examples
assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
assert_eq!("foo:bar".strip_prefix("bar"), None);
assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
1.45.0 · sourcepub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
Returns a string slice with the suffix removed.
If the string ends with the pattern suffix
, returns the substring before the suffix,
wrapped in Some
. Unlike trim_end_matches
, this method removes the suffix exactly once.
If the string does not end with suffix
, returns None
.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Examples
assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
assert_eq!("bar:foo".strip_suffix("bar"), None);
assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
1.30.0 · sourcepub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a strwhere
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a strwhere
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
Returns a string slice with all suffixes that match a pattern repeatedly removed.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Text directionality
A string is a sequence of bytes. end
in this context means the last
position of that byte string; for a left-to-right language like English or
Russian, this will be right side, and for right-to-left languages like
Arabic or Hebrew, this will be the left side.
Examples
Simple patterns:
assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
A more complex pattern, using a closure:
assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
1.0.0 · sourcepub fn trim_left_matches<'a, P>(&'a self, pat: P) -> &'a strwhere
P: Pattern<'a>,
👎Deprecated since 1.33.0: superseded by trim_start_matches
pub fn trim_left_matches<'a, P>(&'a self, pat: P) -> &'a strwhere
P: Pattern<'a>,
trim_start_matches
Returns a string slice with all prefixes that match a pattern repeatedly removed.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Text directionality
A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the right side, not the left.
Examples
Basic usage:
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1.0.0 · sourcepub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a strwhere
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
👎Deprecated since 1.33.0: superseded by trim_end_matches
pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a strwhere
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
trim_end_matches
Returns a string slice with all suffixes that match a pattern repeatedly removed.
The pattern can be a &str
, char
, a slice of char
s, or a
function or closure that determines if a character matches.
Text directionality
A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the left side, not the right.
Examples
Simple patterns:
assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
A more complex pattern, using a closure:
assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
1.0.0 · sourcepub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>where
F: FromStr,
pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>where
F: FromStr,
Parses this string slice into another type.
Because parse
is so general, it can cause problems with type
inference. As such, parse
is one of the few times you’ll see
the syntax affectionately known as the ‘turbofish’: ::<>
. This
helps the inference algorithm understand specifically which type
you’re trying to parse into.
parse
can parse into any type that implements the FromStr
trait.
Errors
Will return Err
if it’s not possible to parse this string slice into
the desired type.
Examples
Basic usage
let four: u32 = "4".parse().unwrap();
assert_eq!(4, four);
Using the ‘turbofish’ instead of annotating four
:
let four = "4".parse::<u32>();
assert_eq!(Ok(4), four);
Failing to parse:
let nope = "j".parse::<u32>();
assert!(nope.is_err());
1.23.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
let ascii = "hello!\n";
let non_ascii = "Grüße, Jürgen ❤";
assert!(ascii.is_ascii());
assert!(!non_ascii.is_ascii());
1.23.0 · sourcepub fn eq_ignore_ascii_case(&self, other: &str) -> bool
pub fn eq_ignore_ascii_case(&self, other: &str) -> bool
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
assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
1.34.0 · sourcepub fn escape_debug(&self) -> EscapeDebug<'_>
pub fn escape_debug(&self) -> EscapeDebug<'_>
Return an iterator that escapes each char in self
with char::escape_debug
.
Note: only extended grapheme codepoints that begin the string will be escaped.
Examples
As an iterator:
for c in "❤\n!".escape_debug() {
print!("{c}");
}
println!();
Using println!
directly:
println!("{}", "❤\n!".escape_debug());
Both are equivalent to:
println!("❤\\n!");
Using to_string
:
assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
1.34.0 · sourcepub fn escape_default(&self) -> EscapeDefault<'_>
pub fn escape_default(&self) -> EscapeDefault<'_>
Return an iterator that escapes each char in self
with char::escape_default
.
Examples
As an iterator:
for c in "❤\n!".escape_default() {
print!("{c}");
}
println!();
Using println!
directly:
println!("{}", "❤\n!".escape_default());
Both are equivalent to:
println!("\\u{{2764}}\\n!");
Using to_string
:
assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
1.34.0 · sourcepub fn escape_unicode(&self) -> EscapeUnicode<'_>
pub fn escape_unicode(&self) -> EscapeUnicode<'_>
Return an iterator that escapes each char in self
with char::escape_unicode
.
Examples
As an iterator:
for c in "❤\n!".escape_unicode() {
print!("{c}");
}
println!();
Using println!
directly:
println!("{}", "❤\n!".escape_unicode());
Both are equivalent to:
println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
Using to_string
:
assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
1.0.0 · sourcepub fn replace<'a, P>(&'a self, from: P, to: &str) -> Stringwhere
P: Pattern<'a>,
Available on non-no_global_oom_handling
only.
pub fn replace<'a, P>(&'a self, from: P, to: &str) -> Stringwhere
P: Pattern<'a>,
no_global_oom_handling
only.Replaces all matches of a pattern with another string.
replace
creates a new String
, and copies the data from this string slice into it.
While doing so, it attempts to find matches of a pattern. If it finds any, it
replaces them with the replacement string slice.
Examples
Basic usage:
let s = "this is old";
assert_eq!("this is new", s.replace("old", "new"));
assert_eq!("than an old", s.replace("is", "an"));
When the pattern doesn’t match:
let s = "this is old";
assert_eq!(s, s.replace("cookie monster", "little lamb"));
1.16.0 · sourcepub fn replacen<'a, P>(&'a self, pat: P, to: &str, count: usize) -> Stringwhere
P: Pattern<'a>,
Available on non-no_global_oom_handling
only.
pub fn replacen<'a, P>(&'a self, pat: P, to: &str, count: usize) -> Stringwhere
P: Pattern<'a>,
no_global_oom_handling
only.Replaces first N matches of a pattern with another string.
replacen
creates a new String
, and copies the data from this string slice into it.
While doing so, it attempts to find matches of a pattern. If it finds any, it
replaces them with the replacement string slice at most count
times.
Examples
Basic usage:
let s = "foo foo 123 foo";
assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
When the pattern doesn’t match:
let s = "this is old";
assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1.2.0 · sourcepub fn to_lowercase(&self) -> String
Available on non-no_global_oom_handling
only.
pub fn to_lowercase(&self) -> String
no_global_oom_handling
only.Returns the lowercase equivalent of this string slice, as a new String
.
‘Lowercase’ is defined according to the terms of the Unicode Derived Core Property
Lowercase
.
Since some characters can expand into multiple characters when changing
the case, this function returns a String
instead of modifying the
parameter in-place.
Examples
Basic usage:
let s = "HELLO";
assert_eq!("hello", s.to_lowercase());
A tricky example, with sigma:
let sigma = "Σ";
assert_eq!("σ", sigma.to_lowercase());
// but at the end of a word, it's ς, not σ:
let odysseus = "ὈΔΥΣΣΕΎΣ";
assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
Languages without case are not changed:
let new_year = "农历新年";
assert_eq!(new_year, new_year.to_lowercase());
1.2.0 · sourcepub fn to_uppercase(&self) -> String
Available on non-no_global_oom_handling
only.
pub fn to_uppercase(&self) -> String
no_global_oom_handling
only.Returns the uppercase equivalent of this string slice, as a new String
.
‘Uppercase’ is defined according to the terms of the Unicode Derived Core Property
Uppercase
.
Since some characters can expand into multiple characters when changing
the case, this function returns a String
instead of modifying the
parameter in-place.
Examples
Basic usage:
let s = "hello";
assert_eq!("HELLO", s.to_uppercase());
Scripts without case are not changed:
let new_year = "农历新年";
assert_eq!(new_year, new_year.to_uppercase());
One character can become multiple:
let s = "tschüß";
assert_eq!("TSCHÜSS", s.to_uppercase());
1.16.0 · sourcepub fn repeat(&self, n: usize) -> String
Available on non-no_global_oom_handling
only.
pub fn repeat(&self, n: usize) -> String
no_global_oom_handling
only.Creates a new String
by repeating a string n
times.
Panics
This function will panic if the capacity would overflow.
Examples
Basic usage:
assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
A panic upon overflow:
// this will panic at runtime
let huge = "0123456789abcdef".repeat(usize::MAX);
1.23.0 · sourcepub fn to_ascii_uppercase(&self) -> String
Available on non-no_global_oom_handling
only.
pub fn to_ascii_uppercase(&self) -> String
no_global_oom_handling
only.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 make_ascii_uppercase
.
To uppercase ASCII characters in addition to non-ASCII characters, use
to_uppercase
.
Examples
let s = "Grüße, Jürgen ❤";
assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
1.23.0 · sourcepub fn to_ascii_lowercase(&self) -> String
Available on non-no_global_oom_handling
only.
pub fn to_ascii_lowercase(&self) -> String
no_global_oom_handling
only.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 make_ascii_lowercase
.
To lowercase ASCII characters in addition to non-ASCII characters, use
to_lowercase
.
Examples
let s = "Grüße, Jürgen ❤";
assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
Trait Implementations§
source§impl<I: Into<Str>> IntoResettable<Str> for I
impl<I: Into<Str>> IntoResettable<Str> for I
source§fn into_resettable(self) -> Resettable<Str>
fn into_resettable(self) -> Resettable<Str>
source§impl IntoResettable<Str> for Option<&'static str>
impl IntoResettable<Str> for Option<&'static str>
source§fn into_resettable(self) -> Resettable<Str>
fn into_resettable(self) -> Resettable<Str>
source§impl Ord for Str
impl Ord for Str
source§impl PartialOrd<Str> for Str
impl PartialOrd<Str> for Str
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