Relevance of `starts_with` and `strip_prefix`

My question is two parts:

  • Is it safe to unwrap str.strip_prefix(p) result when str.starts_with(p) is true where p: impl Pattern?
  • Is it safe to unwrap str.strip_postfix(p) result when str.ends_with(p) is true where p: impl Pattern?

I'm sure this is safe in simple case (see this snippet), but not sure if it was any Pattern.

// let arg: &str = ...
let arg = if arg.starts_with('"') && arg.ends_with('"') {
    arg.strip_suffix('"').unwrap().strip_prefix('"').unwrap()
} else {
    arg
};

If there is no unsafe in sight, then the code is safe. Of course if there is an esoteric Pattern implementation, which is e.g. stateful, then it can pathologically return true when matched for the first time and then return false upon the second invocation. (So, to clarify: you are absolutely not allowed to rely on such behavior for memory safety of unsafe code.)

Why do you need this, though? Why don't you use strip_suffix()/strip_prefix() only, without checking for the match first?

1 Like

You can write it this way to avoid the unwrap:

let mut arg = todo!();
if let Some(s) = arg.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
    arg = s;
}

No, that's not the point.

Of course if there is an esoteric Pattern implementation, which is e.g. stateful, then it can pathologically return true when matched for the first time and then return false upon the second invocation.

Yes, of course Pattern implementation should (or, must) be consistent. However, there's no unsafes on my code, I don't have to worrying about that.

Why do you need this, though? Why don't you use strip_suffix() / strip_prefix() only , without checking for the match first?

Because my code quality is not so good :c