Skip to main content

Pattern

Enum Pattern 

Source
pub enum Pattern {
    Lowercase,
    Uppercase,
    Capital,
    Camel,
    Sentence,
    RemoveEmpty,
    Custom(fn(&[&str]) -> Vec<String>),
}
Expand description

Transformations on a list of words.

A pattern is a function that maps a list of words into another list after changing the casing of each letter. How a patterns mutates each letter can be dependent on the word the letters are present in.

§Custom Pattern

A pattern is a function that maps from a borrowed list of words &[&str] to an owned list of owned words Vec<String> by applying a transformation. One example of custom behavior might be a pattern that detects a fixed list of two-letter acronyms, and capitalizes them appropriately on output.

use convert_case::{Converter, Pattern};

fn pascal_upper_acronyms(words: &[&str]) -> Vec<String> {
    Pattern::Capital.mutate(words).into_iter()
        .map(|word| match word.as_ref() {
            "Io" | "Xml" => word.to_uppercase(),
            _ => word,
        })
        .collect()
}

let acronym_converter = Converter::new()
    .set_patterns(&[Pattern::Custom(pascal_upper_acronyms)]);

assert_eq!(acronym_converter.convert("io_stream"), "IOStream");
assert_eq!(acronym_converter.convert("xml request"), "XMLRequest");

Another example might be a one that explicitly adds leading and trailing double underscores. We do this by modifying the words directly, which will get passed as-is to the join function.

use convert_case::{Converter, Pattern};

fn snake_dunder(mut words: &[&str]) -> Vec<String> {
    words
        .into_iter()
        .map(|word| word.to_lowercase())
        .enumerate()
        .map(|(i, word)| {
            if words.len() == 1 {
                format!("__{}__", word)
            } else if i == 0 {
                format!("__{}", word)
            } else if i == words.len() - 1 {
                format!("{}__", word)
            } else {
                word
            }
        })
        .collect()
}

let dunder_converter = Converter::new()
    .set_patterns(&[Pattern::Custom(snake_dunder)])
    .set_delimiter("_");

assert_eq!(dunder_converter.convert("getAttr"), "__get_attr__");
assert_eq!(dunder_converter.convert("ITER"), "__iter__");

Variants§

§

Lowercase

Makes all words lowercase.

assert_eq!(
    Pattern::Lowercase.mutate(&["Case", "CONVERSION", "library"]),
    vec!["case", "conversion", "library"],
);
§

Uppercase

Makes all words uppercase.

assert_eq!(
    Pattern::Uppercase.mutate(&["Case", "CONVERSION", "library"]),
    vec!["CASE", "CONVERSION", "LIBRARY"],
);
§

Capital

Makes the first letter of each word uppercase and the remaining letters of each word lowercase.

assert_eq!(
    Pattern::Capital.mutate(&["Case", "CONVERSION", "library"]),
    vec!["Case", "Conversion", "Library"],
);
§

Camel

Makes the first non-empty word lowercase and the remaining capitalized.

assert_eq!(
    Pattern::Camel.mutate(&["Case", "CONVERSION", "library"]),
    vec!["case", "Conversion", "Library"],
);
§

Sentence

Makes the first non-empty word capitalized and the remaining lowercase.

assert_eq!(
    Pattern::Sentence.mutate(&["Case", "CONVERSION", "library"]),
    vec!["Case", "conversion", "library"],
);
§

RemoveEmpty

Filters out empty words from the list. Useful when splitting produces empty words from leading/trailing/duplicate delimiters.

assert_eq!(
    Pattern::RemoveEmpty.mutate(&["", "first", "", "second", ""]),
    vec!["first", "second"],
);
§

Custom(fn(&[&str]) -> Vec<String>)

Define custom behavior to transform a set of words.

See the Pattern documentation for examples.

Implementations§

Source§

impl Pattern

Source

pub fn mutate<S>(&self, words: &[S]) -> Vec<String>
where S: AsRef<str>,

Applies the pattern transformation to a list of words.

Trait Implementations§

Source§

impl Clone for Pattern

Source§

fn clone(&self) -> Pattern

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Pattern

Source§

impl Debug for Pattern

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Eq for Pattern

Source§

impl Hash for Pattern

Source§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Pattern

Source§

fn eq(&self, other: &Pattern) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Sync + Send>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.