convert_case/pattern.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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 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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
use std::iter;
#[cfg(feature = "random")]
use rand::prelude::*;
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
enum WordCase {
Lower,
Upper,
Capital,
Toggle,
}
impl WordCase {
fn mutate(&self, word: &str) -> String {
use WordCase::*;
match self {
Lower => word.to_lowercase(),
Upper => word.to_uppercase(),
Capital => {
let mut chars = word.chars();
if let Some(c) = chars.next() {
c.to_uppercase()
.chain(chars.as_str().to_lowercase().chars())
.collect()
} else {
String::new()
}
}
Toggle => {
let mut chars = word.chars();
if let Some(c) = chars.next() {
c.to_lowercase()
.chain(chars.as_str().to_uppercase().chars())
.collect()
} else {
String::new()
}
}
}
}
}
/// A pattern is how a set of words is mutated before joining with
/// a delimeter.
///
/// The `Random` and `PseudoRandom` patterns are used for their respective cases
/// and are only available in the "random" feature.
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum Pattern {
/// Lowercase patterns make all words lowercase.
/// ```
/// use convert_case::Pattern;
/// assert_eq!(
/// vec!["case", "conversion", "library"],
/// Pattern::Lowercase.mutate(&["Case", "CONVERSION", "library"])
/// );
/// ```
Lowercase,
/// Uppercase patterns make all words uppercase.
/// ```
/// use convert_case::Pattern;
/// assert_eq!(
/// vec!["CASE", "CONVERSION", "LIBRARY"],
/// Pattern::Uppercase.mutate(&["Case", "CONVERSION", "library"])
/// );
/// ```
Uppercase,
/// Capital patterns makes the first letter of each word uppercase
/// and the remaining letters of each word lowercase.
/// ```
/// use convert_case::Pattern;
/// assert_eq!(
/// vec!["Case", "Conversion", "Library"],
/// Pattern::Capital.mutate(&["Case", "CONVERSION", "library"])
/// );
/// ```
Capital,
/// Capital patterns make the first word capitalized and the
/// remaining lowercase.
/// ```
/// use convert_case::Pattern;
/// assert_eq!(
/// vec!["Case", "conversion", "library"],
/// Pattern::Sentence.mutate(&["Case", "CONVERSION", "library"])
/// );
/// ```
Sentence,
/// Camel patterns make the first word lowercase and the remaining
/// capitalized.
/// ```
/// use convert_case::Pattern;
/// assert_eq!(
/// vec!["case", "Conversion", "Library"],
/// Pattern::Camel.mutate(&["Case", "CONVERSION", "library"])
/// );
/// ```
Camel,
/// Alternating patterns make each letter of each word alternate
/// between lowercase and uppercase. They alternate across words,
/// which means the last letter of one word and the first letter of the
/// next will not be the same letter casing.
/// ```
/// use convert_case::Pattern;
/// assert_eq!(
/// vec!["cAsE", "cOnVeRsIoN", "lIbRaRy"],
/// Pattern::Alternating.mutate(&["Case", "CONVERSION", "library"])
/// );
/// assert_eq!(
/// vec!["aNoThEr", "ExAmPlE"],
/// Pattern::Alternating.mutate(&["Another", "Example"]),
/// );
/// ```
Alternating,
/// Toggle patterns have the first letter of each word uppercase
/// and the remaining letters of each word uppercase.
/// ```
/// use convert_case::Pattern;
/// assert_eq!(
/// vec!["cASE", "cONVERSION", "lIBRARY"],
/// Pattern::Toggle.mutate(&["Case", "CONVERSION", "library"])
/// );
/// ```
Toggle,
/// Random patterns will lowercase or uppercase each letter
/// uniformly randomly. This uses the `rand` crate and is only available with the "random"
/// feature. This example will not pass the assertion due to randomness, but it used as an
/// example of what output is possible.
/// ```should_panic
/// use convert_case::Pattern;
/// assert_eq!(
/// vec!["Case", "coNVeRSiOn", "lIBraRY"],
/// Pattern::Random.mutate(&["Case", "CONVERSION", "library"])
/// );
/// ```
#[cfg(feature = "random")]
#[cfg(any(doc, feature = "random"))]
Random,
/// PseudoRandom patterns are random-like patterns. Instead of randomizing
/// each letter individually, it mutates each pair of characters
/// as either (Lowercase, Uppercase) or (Uppercase, Lowercase). This generates
/// more "random looking" words. A consequence of this algorithm for randomization
/// is that there will never be three consecutive letters that are all lowercase
/// or all uppercase. This uses the `rand` crate and is only available with the "random"
/// feature. This example will not pass the assertion due to randomness, but it used as an
/// example of what output is possible.
/// ```should_panic
/// use convert_case::Pattern;
/// assert_eq!(
/// vec!["cAsE", "cONveRSioN", "lIBrAry"],
/// Pattern::Random.mutate(&["Case", "CONVERSION", "library"]),
/// );
/// ```
#[cfg(any(doc, feature = "random"))]
PseudoRandom,
}
impl Pattern {
/// Generates a vector of new `String`s in the right pattern given
/// the input strings.
/// ```
/// use convert_case::Pattern;
///
/// assert_eq!(
/// vec!["crack", "the", "skye"],
/// Pattern::Lowercase.mutate(&vec!["CRACK", "the", "Skye"]),
/// )
/// ```
pub fn mutate(&self, words: &[&str]) -> Vec<String> {
use Pattern::*;
match self {
Lowercase => words
.iter()
.map(|word| WordCase::Lower.mutate(word))
.collect(),
Uppercase => words
.iter()
.map(|word| WordCase::Upper.mutate(word))
.collect(),
Capital => words
.iter()
.map(|word| WordCase::Capital.mutate(word))
.collect(),
Toggle => words
.iter()
.map(|word| WordCase::Toggle.mutate(word))
.collect(),
Sentence => {
let word_cases =
iter::once(WordCase::Capital).chain(iter::once(WordCase::Lower).cycle());
words
.iter()
.zip(word_cases)
.map(|(word, word_case)| word_case.mutate(word))
.collect()
}
Camel => {
let word_cases =
iter::once(WordCase::Lower).chain(iter::once(WordCase::Capital).cycle());
words
.iter()
.zip(word_cases)
.map(|(word, word_case)| word_case.mutate(word))
.collect()
}
Alternating => alternating(words),
#[cfg(feature = "random")]
Random => randomize(words),
#[cfg(feature = "random")]
PseudoRandom => pseudo_randomize(words),
}
}
}
fn alternating(words: &[&str]) -> Vec<String> {
let mut upper = false;
words
.iter()
.map(|word| {
word.chars()
.map(|letter| {
if letter.is_uppercase() || letter.is_lowercase() {
if upper {
upper = false;
letter.to_uppercase().to_string()
} else {
upper = true;
letter.to_lowercase().to_string()
}
} else {
letter.to_string()
}
})
.collect()
})
.collect()
}
/// Randomly picks whether to be upper case or lower case
#[cfg(feature = "random")]
fn randomize(words: &[&str]) -> Vec<String> {
let mut rng = rand::thread_rng();
words
.iter()
.map(|word| {
word.chars()
.map(|letter| {
if rng.gen::<f32>() > 0.5 {
letter.to_uppercase().to_string()
} else {
letter.to_lowercase().to_string()
}
})
.collect()
})
.collect()
}
/// Randomly selects patterns: [upper, lower] or [lower, upper]
/// for a more random feeling pattern.
#[cfg(feature = "random")]
fn pseudo_randomize(words: &[&str]) -> Vec<String> {
let mut rng = rand::thread_rng();
// Keeps track of when to alternate
let mut alt: Option<bool> = None;
words
.iter()
.map(|word| {
word.chars()
.map(|letter| {
match alt {
// No existing pattern, start one
None => {
if rng.gen::<f32>() > 0.5 {
alt = Some(false); // Make the next char lower
letter.to_uppercase().to_string()
} else {
alt = Some(true); // Make the next char upper
letter.to_lowercase().to_string()
}
}
// Existing pattern, do what it says
Some(upper) => {
alt = None;
if upper {
letter.to_uppercase().to_string()
} else {
letter.to_lowercase().to_string()
}
}
}
})
.collect()
})
.collect()
}
#[cfg(test)]
mod test {
use super::*;
#[cfg(feature = "random")]
#[test]
fn pseudo_no_triples() {
let words = vec!["abcdefg", "hijklmnop", "qrstuv", "wxyz"];
for _ in 0..5 {
let new = pseudo_randomize(&words).join("");
let mut iter = new
.chars()
.zip(new.chars().skip(1))
.zip(new.chars().skip(2));
assert!(!iter
.clone()
.any(|((a, b), c)| a.is_lowercase() && b.is_lowercase() && c.is_lowercase()));
assert!(
!iter.any(|((a, b), c)| a.is_uppercase() && b.is_uppercase() && c.is_uppercase())
);
}
}
#[cfg(feature = "random")]
#[test]
fn randoms_are_random() {
let words = vec!["abcdefg", "hijklmnop", "qrstuv", "wxyz"];
for _ in 0..5 {
let transformed = pseudo_randomize(&words);
assert_ne!(words, transformed);
let transformed = randomize(&words);
assert_ne!(words, transformed);
}
}
#[test]
fn mutate_empty_strings() {
for wcase in [
WordCase::Lower,
WordCase::Upper,
WordCase::Capital,
WordCase::Toggle,
] {
assert_eq!(String::new(), wcase.mutate(&String::new()))
}
}
}