convert_case/boundary.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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
use unicode_segmentation::UnicodeSegmentation;
fn grapheme_is_digit(c: &&str) -> bool {
c.chars().all(|c| c.is_ascii_digit())
}
fn grapheme_is_uppercase(c: &&str) -> bool {
c.to_uppercase() != c.to_lowercase() && *c == c.to_uppercase()
}
fn grapheme_is_lowercase(c: &&str) -> bool {
c.to_uppercase() != c.to_lowercase() && *c == c.to_lowercase()
}
/// How an identifier is split into words.
///
/// Some boundaries, `HYPHEN`, `UNDERSCORE`, and `SPACE`, consume the character they
/// split on, whereas the other boundaries do not.
///
/// `Boundary` includes methods that return useful groups of boundaries. It also
/// contains the [`defaults_from`](Boundary::defaults_from) method which will generate a subset
/// of default boundaries based on the boundaries present in a string.
///
/// You can also create custom delimiter boundaries using the [`from_delim`](Boundary::from_delim)
/// method or directly instantiate Boundary for complex boundary conditions.
/// ```
/// use convert_case::{Boundary, Case, Casing, Converter};
///
/// assert_eq!(
/// "transformations_in_3d",
/// "TransformationsIn3D"
/// .from_case(Case::Camel)
/// .without_boundaries(&Boundary::digit_letter())
/// .to_case(Case::Snake)
/// );
///
/// let conv = Converter::new()
/// .set_boundaries(&Boundary::defaults_from("aA "))
/// .to_case(Case::Title);
/// assert_eq!("7empest By Tool", conv.convert("7empest byTool"));
/// ```
#[derive(Debug, Eq, Hash, Clone, Copy)]
pub struct Boundary {
/// A unique name used for comparison.
pub name: &'static str,
/// A function that determines if this boundary is present at the start
/// of the string. Second argument is the `arg` field.
pub condition: fn(&[&str], Option<&'static str>) -> bool,
/// An optional string passed to `condition` at runtime. Used
/// internally for [`Boundary::from_delim`] method.
pub arg: Option<&'static str>,
/// Where the beginning of the boundary is.
pub start: usize,
/// The length of the boundary. This is the number of graphemes that
/// are removed when splitting.
pub len: usize,
}
impl PartialEq for Boundary {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
impl Boundary {
/// Splits on space, consuming the character on segmentation.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// vec![Boundary::SPACE],
/// Boundary::defaults_from(" ")
/// );
/// ```
pub const SPACE: Boundary = Boundary {
name: "Space",
condition: |s, _| s.get(0) == Some(&" "),
arg: None,
start: 0,
len: 1,
};
/// Splits on `-`, consuming the character on segmentation.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// vec![Boundary::HYPHEN],
/// Boundary::defaults_from("-")
/// );
/// ```
pub const HYPHEN: Boundary = Boundary {
name: "Hyphen",
condition: |s, _| s.get(0) == Some(&"-"),
arg: None,
start: 0,
len: 1,
};
/// Splits on `_`, consuming the character on segmentation.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// vec![Boundary::UNDERSCORE],
/// Boundary::defaults_from("_")
/// );
/// ```
pub const UNDERSCORE: Boundary = Boundary {
name: "Underscore",
condition: |s, _| s.get(0) == Some(&"_"),
arg: None,
start: 0,
len: 1,
};
/// Splits where a lowercase letter is followed by an uppercase letter.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// vec![Boundary::LOWER_UPPER],
/// Boundary::defaults_from("aA")
/// );
/// ```
pub const LOWER_UPPER: Boundary = Boundary {
name: "LowerUpper",
condition: |s, _| {
s.get(0).map(grapheme_is_lowercase) == Some(true)
&& s.get(1).map(grapheme_is_uppercase) == Some(true)
},
arg: None,
start: 1,
len: 0,
};
/// Splits where an uppercase letter is followed by a lowercase letter. This is seldom used,
/// and is **not** included in the [defaults](Boundary::defaults).
/// ```
/// # use convert_case::Boundary;
/// assert!(
/// Boundary::defaults_from("Aa").len() == 0
/// );
/// ```
pub const UPPER_LOWER: Boundary = Boundary {
name: "UpperLower",
condition: |s, _| {
s.get(0).map(grapheme_is_uppercase) == Some(true)
&& s.get(1).map(grapheme_is_lowercase) == Some(true)
},
arg: None,
start: 1,
len: 0,
};
/// Acronyms are identified by two uppercase letters followed by a lowercase letter.
/// The word boundary is between the two uppercase letters. For example, "HTTPRequest"
/// would have an acronym boundary identified at "PRe" and split into "HTTP" and "Request".
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// vec![Boundary::ACRONYM],
/// Boundary::defaults_from("AAa")
/// );
/// ```
pub const ACRONYM: Boundary = Boundary {
name: "Acronym",
condition: |s, _| {
s.get(0).map(grapheme_is_uppercase) == Some(true)
&& s.get(1).map(grapheme_is_uppercase) == Some(true)
&& s.get(2).map(grapheme_is_lowercase) == Some(true)
},
arg: None,
start: 1,
len: 0,
};
/// Splits where a lowercase letter is followed by a digit.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// vec![Boundary::LOWER_DIGIT],
/// Boundary::defaults_from("a1")
/// );
/// ```
pub const LOWER_DIGIT: Boundary = Boundary {
name: "LowerDigit",
condition: |s, _| {
s.get(0).map(grapheme_is_lowercase) == Some(true)
&& s.get(1).map(grapheme_is_digit) == Some(true)
},
arg: None,
start: 1,
len: 0,
};
/// Splits where an uppercase letter is followed by a digit.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// vec![Boundary::UPPER_DIGIT],
/// Boundary::defaults_from("A1")
/// );
/// ```
pub const UPPER_DIGIT: Boundary = Boundary {
name: "UpperDigit",
condition: |s, _| {
s.get(0).map(grapheme_is_uppercase) == Some(true)
&& s.get(1).map(grapheme_is_digit) == Some(true)
},
arg: None,
start: 1,
len: 0,
};
/// Splits where digit is followed by a lowercase letter.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// vec![Boundary::DIGIT_LOWER],
/// Boundary::defaults_from("1a")
/// );
/// ```
pub const DIGIT_LOWER: Boundary = Boundary {
name: "DigitLower",
condition: |s, _| {
s.get(0).map(grapheme_is_digit) == Some(true)
&& s.get(1).map(grapheme_is_lowercase) == Some(true)
},
arg: None,
start: 1,
len: 0,
};
/// Splits where digit is followed by an uppercase letter.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// vec![Boundary::DIGIT_UPPER],
/// Boundary::defaults_from("1A")
/// );
/// ```
pub const DIGIT_UPPER: Boundary = Boundary {
name: "DigitUpper",
condition: |s, _| {
s.get(0).map(grapheme_is_digit) == Some(true)
&& s.get(1).map(grapheme_is_uppercase) == Some(true)
},
arg: None,
start: 1,
len: 0,
};
/// Create a new boundary based on a delimiter.
/// ```
/// # use convert_case::{Case, Converter, Boundary};
/// let conv = Converter::new()
/// .set_boundaries(&[Boundary::from_delim("::")])
/// .to_case(Case::Camel);
/// assert_eq!(
/// "myVarName",
/// conv.convert("my::var::name")
/// )
/// ```
pub const fn from_delim(delim: &'static str) -> Boundary {
Boundary {
name: delim,
arg: Some(delim),
condition: |s, arg| s.join("").starts_with(arg.unwrap()),
start: 0,
len: delim.len(),
}
}
/// The default list of boundaries used when `Casing::to_case` is called directly
/// and in a `Converter` generated from `Converter::new()`.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// [
/// Boundary::SPACE,
/// Boundary::HYPHEN,
/// Boundary::UNDERSCORE,
/// Boundary::LOWER_UPPER,
/// Boundary::ACRONYM,
/// Boundary::LOWER_DIGIT,
/// Boundary::UPPER_DIGIT,
/// Boundary::DIGIT_LOWER,
/// Boundary::DIGIT_UPPER,
/// ],
/// Boundary::defaults()
/// );
/// ```
pub const fn defaults() -> [Boundary; 9] {
[
Boundary::SPACE,
Boundary::HYPHEN,
Boundary::UNDERSCORE,
Boundary::LOWER_UPPER,
Boundary::ACRONYM,
Boundary::LOWER_DIGIT,
Boundary::UPPER_DIGIT,
Boundary::DIGIT_LOWER,
Boundary::DIGIT_UPPER,
]
}
/// Returns the boundaries that involve digits.
/// `LowerDigit`.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// [
/// Boundary::LOWER_DIGIT,
/// Boundary::UPPER_DIGIT,
/// Boundary::DIGIT_LOWER,
/// Boundary::DIGIT_UPPER,
/// ],
/// Boundary::digits()
/// );
/// ```
pub const fn digits() -> [Boundary; 4] {
[
Boundary::LOWER_DIGIT,
Boundary::UPPER_DIGIT,
Boundary::DIGIT_LOWER,
Boundary::DIGIT_UPPER,
]
}
/// Returns the boundaries that are letters followed by digits.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// [
/// Boundary::LOWER_DIGIT,
/// Boundary::UPPER_DIGIT,
/// ],
/// Boundary::letter_digit()
/// );
/// ```
pub const fn letter_digit() -> [Boundary; 2] {
[Boundary::LOWER_DIGIT, Boundary::UPPER_DIGIT]
}
/// Returns the boundaries that are digits followed by letters.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// [
/// Boundary::DIGIT_LOWER,
/// Boundary::DIGIT_UPPER
/// ],
/// Boundary::digit_letter()
/// );
/// ```
pub fn digit_letter() -> [Boundary; 2] {
[Boundary::DIGIT_LOWER, Boundary::DIGIT_UPPER]
}
/// Returns a list of all boundaries that are identified within the given string.
/// Could be a short of writing out all the boundaries in a list directly. This will not
/// identify boundary `UpperLower` if it also used as part of `Acronym`.
///
/// If you want to be very explicit and not overlap boundaries, it is recommended to use a colon
/// character.
/// ```
/// # use convert_case::Boundary;
/// assert_eq!(
/// vec![
/// Boundary::SPACE,
/// Boundary::HYPHEN,
/// Boundary::LOWER_UPPER,
/// Boundary::UPPER_DIGIT,
/// Boundary::DIGIT_LOWER,
/// ],
/// Boundary::defaults_from("aA8a -")
/// );
/// assert_eq!(
/// vec![
/// Boundary::UNDERSCORE,
/// Boundary::LOWER_UPPER,
/// Boundary::ACRONYM,
/// Boundary::DIGIT_UPPER,
/// ],
/// Boundary::defaults_from("bD:0B:_:AAa")
/// );
/// ```
pub fn defaults_from(pattern: &str) -> Vec<Boundary> {
let mut boundaries = Vec::new();
for boundary in Boundary::defaults() {
let parts = split(&pattern, &[boundary]);
if parts.len() > 1 || parts.len() == 0 || parts[0] != pattern {
boundaries.push(boundary);
}
}
boundaries
}
}
/// Split an identifier into a list of words using the list of boundaries.
///
/// This is used internally for splitting an identifier before mutating by
/// a pattern and joining again with a delimiter.
/// ```
/// use convert_case::{Boundary, split};
/// assert_eq!(
/// vec!["one", "two", "three.four"],
/// split(&"one_two-three.four", &[Boundary::UNDERSCORE, Boundary::HYPHEN]),
/// )
/// ```
pub fn split<'s, T>(s: &'s T, boundaries: &[Boundary]) -> Vec<&'s str>
where
T: AsRef<str>,
{
let s = s.as_ref();
if s.len() == 0 {
return vec![];
}
let mut words = Vec::new();
let mut last_boundary_end = 0;
let (indices, graphemes): (Vec<_>, Vec<_>) = s.grapheme_indices(true).unzip();
let grapheme_length = indices[graphemes.len() - 1] + graphemes[graphemes.len() - 1].len();
for i in 0..graphemes.len() {
for boundary in boundaries {
//let byte_index = indices[i];
if (boundary.condition)(&graphemes[i..], boundary.arg) {
// What if we find a condition at the end of the array?
// Maybe we can stop early based on length
// To do this, need to switch the loops
// TODO
let boundary_byte_start: usize =
*indices.get(i + boundary.start).unwrap_or(&grapheme_length);
let boundary_byte_end: usize = *indices
.get(i + boundary.start + boundary.len)
.unwrap_or(&grapheme_length);
// todo clean this up a bit
words.push(&s[last_boundary_end..boundary_byte_start]);
last_boundary_end = boundary_byte_end;
break;
}
}
}
words.push(&s[last_boundary_end..]);
words.into_iter().filter(|s| !s.is_empty()).collect()
}
// ascii version
//pub fn split<'s, T>(s: &'s T, boundaries: &[Boundary]) -> Vec<&'s str>
//where
// T: AsRef<str>,
//{
// let s = s.as_ref();
//
// let mut words = Vec::new();
// let mut last_end = 0;
// for i in 0..s.len() {
// for boundary in boundaries {
// if (boundary.condition)(&s[i..]) {
// words.push(&s[last_end..i + boundary.start]);
// last_end = i + boundary.start + boundary.len;
// break;
// }
// }
// }
// words.push(&s[last_end..]);
// words
//}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hyphen() {
let s = "a-b-c";
let v = split(&s, &[Boundary::HYPHEN]);
assert_eq!(v, vec!["a", "b", "c"]);
}
#[test]
fn underscore() {
let s = "a_b_c";
let v = split(&s, &[Boundary::UNDERSCORE]);
assert_eq!(v, vec!["a", "b", "c"]);
}
#[test]
fn space() {
let s = "a b c";
let v = split(&s, &[Boundary::SPACE]);
assert_eq!(v, vec!["a", "b", "c"]);
}
#[test]
fn delimiters() {
let s = "aaa-bbb_ccc ddd ddd-eee";
let v = split(
&s,
&[Boundary::SPACE, Boundary::UNDERSCORE, Boundary::HYPHEN],
);
assert_eq!(v, vec!["aaa", "bbb", "ccc", "ddd", "ddd", "eee"]);
}
#[test]
fn lower_upper() {
let s = "lowerUpperUpper";
let v = split(&s, &[Boundary::LOWER_UPPER]);
assert_eq!(v, vec!["lower", "Upper", "Upper"]);
}
#[test]
fn acronym() {
let s = "XMLRequest";
let v = split(&s, &[Boundary::ACRONYM]);
assert_eq!(v, vec!["XML", "Request"]);
}
// TODO: add tests for other boundaries
#[test]
fn boundaries_found_in_string() {
// upper lower is not longer a default
assert_eq!(Vec::<Boundary>::new(), Boundary::defaults_from(".Aaaa"));
assert_eq!(
vec![Boundary::LOWER_UPPER, Boundary::LOWER_DIGIT,],
Boundary::defaults_from("a8.Aa.aA")
);
assert_eq!(
Boundary::digits().to_vec(),
Boundary::defaults_from("b1B1b")
);
assert_eq!(
vec![
Boundary::SPACE,
Boundary::HYPHEN,
Boundary::UNDERSCORE,
Boundary::ACRONYM,
],
Boundary::defaults_from("AAa -_")
);
}
#[test]
fn boundary_consts_same() {
assert_eq!(Boundary::SPACE, Boundary::SPACE);
}
#[test]
fn from_delim_dot() {
let boundary = Boundary::from_delim(".");
let s = "lower.Upper.Upper";
let v = split(&s, &[boundary]);
assert_eq!(vec!["lower", "Upper", "Upper"], v)
}
#[test]
fn from_delim_double_colon() {
let boundary = Boundary::from_delim("::");
let s = "lower::lowerUpper::Upper";
let v = split(&s, &[boundary]);
assert_eq!(vec!["lower", "lowerUpper", "Upper"], v)
}
}