#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]
#![cfg_attr(feature = "nightly", feature(iter_intersperse))]
#![cfg_attr(feature = "nightly", feature(doc_cfg))]
mod iter;
use iter::CapitalizeIterator;
pub trait Capitalize: AsRef<str> {
fn capitalize(&self) -> String;
#[cfg(feature = "nightly")]
#[doc(cfg(feature = "nightly"))]
fn capitalize_words(&self) -> String;
fn capitalize_first_only(&self) -> String;
fn capitalize_last_only(&self) -> String;
}
impl<T: AsRef<str>> Capitalize for T {
fn capitalize(&self) -> String {
let string = self.as_ref();
let mut buf = String::with_capacity(string.len());
buf.extend(string.chars().capitalize());
return buf;
}
#[cfg(feature = "nightly")]
fn capitalize_words(&self) -> String {
if self.as_ref().is_empty() {
return String::with_capacity(0);
}
self.as_ref()
.split(" ")
.intersperse(" ")
.map(|item| item.chars().capitalize())
.flatten()
.collect()
}
fn capitalize_first_only(&self) -> String {
let mut chars = self.as_ref().chars();
let Some(first) = chars.next() else {
return String::with_capacity(0);
};
first.to_uppercase().chain(chars).collect()
}
fn capitalize_last_only(&self) -> String {
let mut chars = self.as_ref().chars().rev();
let Some(last) = chars.next() else {
return String::with_capacity(0);
};
last.to_uppercase().chain(chars).rev().collect()
}
}
#[cfg(test)]
mod test {
use super::Capitalize;
#[test]
fn string_reference() {
let text = String::from("hello ✨ World");
let text_ref = &text;
assert_eq!(text_ref.capitalize(), "Hello ✨ world");
}
#[test]
fn capitalize_first_only_reference() {
let text = String::from("heLLo ✨ World");
let text_ref = &text;
assert_eq!(text_ref.capitalize_first_only(), "HeLLo ✨ World");
}
#[test]
fn capitalize_final_only_reference() {
let text = String::from("heLLo ✨ World");
let text_ref = &text;
assert_eq!(text_ref.capitalize_last_only(), "heLLo ✨ WorlD");
}
}