-
Notifications
You must be signed in to change notification settings - Fork 2
/
lib.rs
488 lines (452 loc) · 15.7 KB
/
lib.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
//! This crate is an implementation of the Unicode Title Casing algorithm. It implements a trait
//! on [char] and [str] that adds title case handling methods. These methods are very similar to how
//! the std library currently handles uppercase and lowercase.
#![no_std]
#![deny(missing_docs)]
#![deny(rustdoc::missing_doc_code_examples)]
#![deny(unsafe_code)]
#![warn(clippy::pedantic)]
extern crate alloc;
use alloc::string::String;
use core::fmt::{Debug, Display, Formatter, Result, Write};
use core::iter::FusedIterator;
include!(concat!(env!("OUT_DIR"), "/casing.rs"));
#[allow(clippy::doc_link_with_quotes)]
/// Accepts a char and returns the Unicode Title Case for that character as a 3 char array.
///
/// # Examples
/// If the character is already titlecase then it will return itself:
/// ```
/// use unicode_titlecase::to_titlecase;
/// assert_eq!(to_titlecase('A'), ['A', '\0', '\0']);
/// ```
/// Single-char characters are mapped:
/// ```
/// use unicode_titlecase::to_titlecase;
/// assert_eq!(to_titlecase('DŽ'), ['Dž', '\0', '\0']);
/// ```
/// Multi-char ligatures are converted:
/// ```
/// use unicode_titlecase::to_titlecase;
/// assert_eq!(to_titlecase('ffl'), ['F', 'f', 'l']);
/// ```
/// Locale is ignored:
/// ```
/// use unicode_titlecase::to_titlecase;
/// assert_eq!(to_titlecase('i'), ['I', '\0', '\0']);
/// ```
/// # Locale
/// This function is not locale specific. Unicode special casing has rules for tr and az that
/// this function does not take into account. For tr and az locales use [`to_titlecase_tr_or_az`]
#[must_use]
pub fn to_titlecase(c: char) -> [char; 3] {
if let Ok(index) = TITLECASE_TABLE.binary_search_by(|&(key, _)| key.cmp(&c)) {
TITLECASE_TABLE[index].1
} else {
[c, '\0', '\0']
}
}
#[allow(clippy::doc_link_with_quotes)]
/// Accepts a char and returns the Unicode Title Case for that character as a 3 char array.
///
/// # Examples
/// If the character is already titlecase then it will return itself:
/// ```
/// use unicode_titlecase::to_titlecase_tr_or_az;
/// assert_eq!(to_titlecase_tr_or_az('A'), ['A', '\0', '\0']);
/// ```
/// Single-char characters are mapped:
/// ```
/// use unicode_titlecase::to_titlecase_tr_or_az;
/// assert_eq!(to_titlecase_tr_or_az('DŽ'), ['Dž', '\0', '\0']);
/// ```
/// Multi-char ligatures are converted:
/// ```
/// use unicode_titlecase::to_titlecase_tr_or_az;
/// assert_eq!(to_titlecase_tr_or_az('ffl'), ['F', 'f', 'l']);
/// ```
/// Locale is tr/az:
/// ```
/// use unicode_titlecase::to_titlecase_tr_or_az;
/// assert_eq!(to_titlecase_tr_or_az('i'), ['İ', '\0', '\0']);
/// ```
/// # Locale
/// This function is specific to the tr and az locales. It returns different results for certain
/// chars. To use locale agnostic version see [`to_titlecase`].
#[must_use]
pub fn to_titlecase_tr_or_az(c: char) -> [char; 3] {
if c == '\u{0069}' {
['\u{0130}', '\0', '\0']
} else {
to_titlecase(c)
}
}
/// This trait adds title case methods to [`char`]. They function the same as the std library's
/// [`char::to_lowercase`] and [`char::to_uppercase`] using a custom [`ToTitleCase`] iterator.
pub trait TitleCase {
/// Wraps [`to_titlecase`] in an iterator. The iterator will yield at most 3 chars.
///
/// # Examples
/// If the character is already titlecase then it will return itself
/// ```
/// use unicode_titlecase::TitleCase;
/// assert_eq!('A'.to_titlecase().to_string(), "A")
/// ```
/// Single-char characters are mapped:
/// ```
/// use unicode_titlecase::TitleCase;
/// assert_eq!('DŽ'.to_titlecase().to_string(), "Dž")
/// ```
/// Multi-char ligatures are converted:
/// ```
/// use unicode_titlecase::TitleCase;
/// assert_eq!('ffl'.to_titlecase().to_string(), "Ffl")
/// ```
/// Locale is ignored:
/// ```
/// use unicode_titlecase::TitleCase;
/// assert_eq!('i'.to_titlecase().to_string(), "I")
/// ```
/// # Locale
/// This function is not locale specific. Unicode special casing has rules for tr and az that
/// this function does not take into account. For tr and az locales use [`TitleCase::to_titlecase_tr_or_az`]
fn to_titlecase(self) -> ToTitleCase;
/// Wraps [`to_titlecase_tr_or_az`] in an iterator. The iterator will yield at most 3 chars.
///
/// # Examples
/// If the character is already titlecase then it will return itself
/// ```
/// use unicode_titlecase::TitleCase;
/// assert_eq!('A'.to_titlecase_tr_or_az().to_string(), "A")
/// ```
/// Single-char characters are mapped:
/// ```
/// use unicode_titlecase::TitleCase;
/// assert_eq!('DŽ'.to_titlecase_tr_or_az().to_string(), "Dž")
/// ```
/// Multi-char ligatures are converted:
/// ```
/// use unicode_titlecase::TitleCase;
/// assert_eq!('ffl'.to_titlecase_tr_or_az().to_string(), "Ffl")
/// ```
/// Locale is tr/az:
/// ```
/// use unicode_titlecase::TitleCase;
/// assert_eq!('i'.to_titlecase_tr_or_az().to_string(), "İ")
/// ```
///
/// # Locale
/// This function is specific to the tr and az locales. It returns different results for certain
/// chars. To use locale agnostic version see [`TitleCase::to_titlecase`].
fn to_titlecase_tr_or_az(self) -> ToTitleCase;
/// Returns true if the given character is a titlecase character. This function works for all locales
/// including tr and az.
/// # Examples
/// ```
/// use unicode_titlecase::TitleCase;
/// assert!('A'.is_titlecase());
/// assert!('Dž'.is_titlecase());
/// assert!('İ'.is_titlecase());
///
/// assert!(!'a'.is_titlecase());
/// assert!(!'DŽ'.is_titlecase());
/// assert!(!'ffl'.is_titlecase());
/// ```
fn is_titlecase(&self) -> bool;
}
impl TitleCase for char {
fn to_titlecase(self) -> ToTitleCase {
ToTitleCase(CaseMappingIter::new(to_titlecase(self)))
}
fn to_titlecase_tr_or_az(self) -> ToTitleCase {
ToTitleCase(CaseMappingIter::new(to_titlecase_tr_or_az(self)))
}
fn is_titlecase(&self) -> bool {
TITLECASE_TABLE
.binary_search_by(|&(key, _)| key.cmp(self))
.is_err()
}
}
/// Trait to add titlecase operations to Strings and string slices. Both locale agnostic and TR/AZ
/// versions of the functions are supplied.
pub trait StrTitleCase {
/// Titlecases the first char of a string, leaves the rest unchanged, and returns a copy.
///
/// # Examples
/// If the str is already titlecase then it will return itself
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert_eq!("ABC".to_titlecase(), "ABC")
/// ```
/// Single-char characters are mapped:
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert_eq!("DŽDŽ".to_titlecase(), "DžDŽ")
/// ```
/// Multi-char ligatures are converted:
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert_eq!("fflabc".to_titlecase(), "Fflabc")
/// ```
/// Locale is ignored:
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert_eq!("iii".to_titlecase(), "Iii")
/// ```
/// # Locale
/// This function is not locale specific. Unicode special casing has rules for tr and az that
/// this function does not take into account. For tr and az locales use [`StrTitleCase::to_titlecase_tr_or_az`]
fn to_titlecase(&self) -> String;
/// Titlecases the first char of a string, lowercases the rest of the string, and returns a copy.
///
/// # Examples
/// If the str is already titlecase then it will return itself
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert_eq!("ABC".to_titlecase_lower_rest(), "Abc")
/// ```
/// Single-char characters are mapped:
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert_eq!("DŽDŽ".to_titlecase_lower_rest(), "Dždž")
/// ```
/// Multi-char ligatures are converted:
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert_eq!("fflabc".to_titlecase_lower_rest(), "Fflabc")
/// ```
/// Locale is ignored:
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert_eq!("iIi".to_titlecase_lower_rest(), "Iii")
/// ```
/// # Locale
/// This function is not locale specific. Unicode special casing has rules for tr and az that
/// this function does not take into account. For tr and az locales use [`StrTitleCase::to_titlecase_tr_or_az_lower_rest`]
fn to_titlecase_lower_rest(&self) -> String;
/// This functions the same way as [`StrTitleCase::to_titlecase`] except that it uses the TR/AZ
/// locales. This has one major change:
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert_eq!("iIi".to_titlecase_tr_or_az(), "İIi")
/// ```
///
/// For the locale agnostic version use [`StrTitleCase::to_titlecase`].
fn to_titlecase_tr_or_az(&self) -> String;
/// This functions the same way as [`StrTitleCase::to_titlecase_lower_rest`] except that it uses
/// the TR/AZ locales. This has one major change:
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert_eq!("iIi".to_titlecase_tr_or_az_lower_rest(), "İii")
/// ```
///
/// For the locale agnostic version use [`StrTitleCase::to_titlecase_lower_rest`].
fn to_titlecase_tr_or_az_lower_rest(&self) -> String;
/// Tests if the first char of this string is titlecase. This is locale agnostic and returns the
/// same values in the tr/az locales.
/// # Returns
/// True if the first character of the string is title case, ignoring the rest of the string.
/// False if first character is not title case or the string is empty.
/// # Examples
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert!("Abc".starts_titlecase());
/// assert!("ABC".starts_titlecase());
///
/// assert!(!"abc".starts_titlecase());
/// ```
fn starts_titlecase(&self) -> bool;
/// Tests if the first char of this string is titlecase and the rest of the string is lowercase.
/// This is locale agnostic and returns the same values in the tr/az locales.
/// # Returns
/// True if the first character of the string is title case and the rest of the string is lowercase.
/// False if first character is not title case or the string is empty.
/// # Examples
/// ```
/// use unicode_titlecase::StrTitleCase;
/// assert!("Abc".starts_titlecase_rest_lower());
/// assert!("İbc".starts_titlecase_rest_lower());
///
/// assert!(!"abc".starts_titlecase_rest_lower());
/// assert!(!"ABC".starts_titlecase_rest_lower());
/// assert!(!"İİ".starts_titlecase_rest_lower());
/// ```
fn starts_titlecase_rest_lower(&self) -> bool;
}
impl StrTitleCase for str {
fn to_titlecase(&self) -> String {
let mut iter = self.chars();
iter.next()
.into_iter()
.flat_map(TitleCase::to_titlecase)
.chain(iter)
.collect()
}
fn to_titlecase_lower_rest(&self) -> String {
let mut iter = self.chars();
iter.next()
.into_iter()
.flat_map(TitleCase::to_titlecase)
.chain(iter.flat_map(char::to_lowercase))
.collect()
}
fn to_titlecase_tr_or_az(&self) -> String {
let mut iter = self.chars();
iter.next()
.into_iter()
.flat_map(TitleCase::to_titlecase_tr_or_az)
.chain(iter)
.collect()
}
fn to_titlecase_tr_or_az_lower_rest(&self) -> String {
let mut iter = self.chars();
iter.next()
.into_iter()
.flat_map(TitleCase::to_titlecase_tr_or_az)
.chain(iter.flat_map(char::to_lowercase))
.collect()
}
fn starts_titlecase(&self) -> bool {
self.chars()
.next()
.as_ref()
.map_or(false, TitleCase::is_titlecase)
}
fn starts_titlecase_rest_lower(&self) -> bool {
let mut iter = self.chars();
iter.next()
.as_ref()
.map_or(false, TitleCase::is_titlecase)
&& iter.all(char::is_lowercase)
}
}
/// An iterator over a titlecase mapped char.
///
/// Copied from the std library's [`core::char::ToLowercase`] and [`core::char::ToUppercase`].
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct ToTitleCase(CaseMappingIter);
impl Iterator for ToTitleCase {
type Item = char;
fn next(&mut self) -> Option<char> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl DoubleEndedIterator for ToTitleCase {
fn next_back(&mut self) -> Option<char> {
self.0.next_back()
}
}
impl FusedIterator for ToTitleCase {}
impl ExactSizeIterator for ToTitleCase {}
impl Display for ToTitleCase {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
core::fmt::Display::fmt(&self.0, f)
}
}
// Copied out of the std library
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
enum CaseMappingIter {
Three(char, char, char),
Two(char, char),
One(char),
Zero,
}
impl CaseMappingIter {
fn new(chars: [char; 3]) -> CaseMappingIter {
if chars[2] == '\0' {
if chars[1] == '\0' {
CaseMappingIter::One(chars[0]) // Including if chars[0] == '\0'
} else {
CaseMappingIter::Two(chars[0], chars[1])
}
} else {
CaseMappingIter::Three(chars[0], chars[1], chars[2])
}
}
}
impl Iterator for CaseMappingIter {
type Item = char;
fn next(&mut self) -> Option<char> {
match *self {
CaseMappingIter::Three(a, b, c) => {
*self = CaseMappingIter::Two(b, c);
Some(a)
}
CaseMappingIter::Two(b, c) => {
*self = CaseMappingIter::One(c);
Some(b)
}
CaseMappingIter::One(c) => {
*self = CaseMappingIter::Zero;
Some(c)
}
CaseMappingIter::Zero => None,
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let size = match self {
CaseMappingIter::Three(..) => 3,
CaseMappingIter::Two(..) => 2,
CaseMappingIter::One(_) => 1,
CaseMappingIter::Zero => 0,
};
(size, Some(size))
}
}
impl DoubleEndedIterator for CaseMappingIter {
fn next_back(&mut self) -> Option<char> {
match *self {
CaseMappingIter::Three(a, b, c) => {
*self = CaseMappingIter::Two(a, b);
Some(c)
}
CaseMappingIter::Two(b, c) => {
*self = CaseMappingIter::One(b);
Some(c)
}
CaseMappingIter::One(c) => {
*self = CaseMappingIter::Zero;
Some(c)
}
CaseMappingIter::Zero => None,
}
}
}
impl Display for CaseMappingIter {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match *self {
CaseMappingIter::Three(a, b, c) => {
f.write_char(a)?;
f.write_char(b)?;
f.write_char(c)
}
CaseMappingIter::Two(b, c) => {
f.write_char(b)?;
f.write_char(c)
}
CaseMappingIter::One(c) => f.write_char(c),
CaseMappingIter::Zero => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
include!(concat!(env!("OUT_DIR"), "/casing.rs"));
#[test]
fn self_mapping() {
TITLECASE_TABLE.iter().for_each(|(cp, mapping)| {
assert_ne!(*cp, mapping[0]);
});
}
#[test]
fn is_sorted() {
let mut last = '\0';
TITLECASE_TABLE.iter().for_each(|(cp, _)| {
assert!(*cp > last, "cp: {cp}, last: {last}");
last = *cp;
});
}
}