ReplaceString

Trait ReplaceString 

Source
pub trait ReplaceString {
    // Required methods
    fn remove_all_ascii(&self, ch: AsciiChar) -> Cow<'_, str>;
    fn replace_all_str(&self, from: &str, to: &str) -> Cow<'_, str>;
}
Expand description

Trait for string replacement operations that return a Cow<str>.

This trait provides methods for string manipulations that avoid unnecessary allocations when no changes are needed, returning Cow::Borrowed for unchanged strings and Cow::Owned for modified strings.

Required Methods§

Source

fn remove_all_ascii(&self, ch: AsciiChar) -> Cow<'_, str>

Removes all occurrences of the specified ASCII character from the string.

§Arguments
  • ch - The ASCII character to remove from the string
§Returns
  • Cow::Borrowed - If the character is not found in the string (no allocation needed)
  • Cow::Owned - If the character is found and removed (new string allocated)
§Examples
use cow_replace::ReplaceString;
use ascii::AsciiChar;
use std::borrow::Cow;

let text = "hello world";
let result = text.remove_all_ascii(AsciiChar::l);
assert_eq!(result, "heo word");

// No allocation when character not found
let result = text.remove_all_ascii(AsciiChar::z);
match result {
    Cow::Borrowed(_) => println!("No allocation needed!"),
    Cow::Owned(_) => unreachable!(),
}
Source

fn replace_all_str(&self, from: &str, to: &str) -> Cow<'_, str>

Replaces all occurrences of a substring with another substring.

§Arguments
  • from - The substring to search for and replace
  • to - The replacement substring
§Returns
  • Cow::Borrowed - If from is not found in the string (no allocation needed)
  • Cow::Owned - If replacements were made (new string allocated)
§Examples
use cow_replace::ReplaceString;
use std::borrow::Cow;

let text = "hello world hello";
let result = text.replace_all_str("hello", "hi");
assert_eq!(result, "hi world hi");

// No allocation when substring not found
let result = text.replace_all_str("xyz", "abc");
match result {
    Cow::Borrowed(_) => println!("No allocation needed!"),
    Cow::Owned(_) => unreachable!(),
}

Implementors§