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
#![doc(html_root_url = "https://djudd.github.io/human-name/")]
#![feature(libc)]
#![feature(plugin)]
#![plugin(phf_macros)]
extern crate phf;
extern crate itertools;
extern crate unicode_segmentation;
extern crate unicode_normalization;
extern crate unidecode;
extern crate rustc_serialize;
#[macro_use]
mod utils;
mod suffix;
mod nickname;
mod title;
mod surname;
mod namecase;
mod namepart;
mod parse;
mod comparison;
mod serialization;
mod web_match;
pub mod external;
#[cfg(feature = "name_eq_hash")]
mod eq_hash;
use std::borrow::Cow;
use std::cell::Cell;
use std::hash::{Hash, Hasher, SipHasher};
use std::slice::Iter;
use std::str::Chars;
use std::iter::{Peekable, Enumerate};
use itertools::Itertools;
use utils::{is_mixed_case, transliterate, lowercase_if_alpha};
pub struct Name {
words: Vec<String>,
surname_index: usize,
generation_from_suffix: Option<usize>,
initials: String,
word_indices_in_initials: Vec<(usize, usize)>,
hash: Cell<Option<u64>>,
}
impl Name {
pub fn parse(name: &str) -> Option<Name> {
if name.len() >= 1000 || !name.chars().any(char::is_alphabetic) {
return None;
}
let mixed_case = is_mixed_case(name);
let name = nickname::strip_nickname(name);
let result = parse::parse(&*name, mixed_case);
if result.is_none() {
return None;
}
let (words, surname_index, generation_from_suffix) = result.unwrap();
let mut names: Vec<String> = Vec::with_capacity(words.len());
let mut initials = String::with_capacity(surname_index);
let mut surname_index_in_names = surname_index;
let mut word_indices_in_initials: Vec<(usize, usize)> = Vec::with_capacity(surname_index);
for (i, word) in words.into_iter().enumerate() {
if word.is_initials() && i < surname_index {
initials.extend(word.namecased
.chars()
.filter(|c| c.is_alphabetic())
.flat_map(|c| c.to_uppercase()));
surname_index_in_names -= 1;
} else if i < surname_index {
let prior_len = initials.len();
initials.extend(word.namecased
.split('-')
.filter_map(|w| w.chars().find(|c| c.is_alphabetic())));
names.push(word.namecased.into_owned());
word_indices_in_initials.push((prior_len, initials.len()));
} else {
names.push(word.namecased.into_owned());
}
}
names.shrink_to_fit();
word_indices_in_initials.shrink_to_fit();
Some(Name {
words: names,
surname_index: surname_index_in_names,
generation_from_suffix: generation_from_suffix,
initials: initials,
word_indices_in_initials: word_indices_in_initials,
hash: Cell::new(None),
})
}
pub fn first_initial(&self) -> char {
self.initials.chars().nth(0).unwrap()
}
pub fn given_name(&self) -> Option<&str> {
if self.surname_index > 0 {
Some(&*self.words[0])
} else {
None
}
}
pub fn goes_by_middle_name(&self) -> bool {
!self.word_indices_in_initials.is_empty() && self.word_indices_in_initials[0].0 > 0
}
pub fn initials(&self) -> &str {
&self.initials
}
pub fn middle_names(&self) -> Option<&[String]> {
if self.surname_index > 1 {
Some(&self.words[1..self.surname_index])
} else {
None
}
}
pub fn middle_name(&self) -> Option<Cow<str>> {
match self.middle_names() {
Some(words) => {
if words.len() == 1 {
Some(Cow::Borrowed(&*words[0]))
} else {
Some(Cow::Owned(words.join(" ")))
}
}
None => None,
}
}
pub fn middle_initials(&self) -> Option<&str> {
match self.initials().char_indices().skip(1).nth(0) {
Some((i, _)) => Some(&self.initials[i..]),
None => None,
}
}
pub fn surnames(&self) -> &[String] {
&self.words[self.surname_index..]
}
pub fn surname(&self) -> Cow<str> {
if self.surnames().len() > 1 {
Cow::Owned(self.surnames().join(" "))
} else {
Cow::Borrowed(&*self.surnames()[0])
}
}
pub fn suffix(&self) -> Option<&str> {
self.generation_from_suffix.map(|g| suffix::display_generational_suffix(g))
}
fn given_names_or_initials(&self) -> GivenNamesOrInitials {
GivenNamesOrInitials {
initials: self.initials.chars().enumerate(),
known_names: self.words[0..self.surname_index].iter(),
known_name_indices: self.word_indices_in_initials.iter().peekable(),
}
}
pub fn display_initial_surname(&self) -> String {
format!("{}. {}", self.first_initial(), self.surname())
}
pub fn display_first_last(&self) -> String {
match self.given_name() {
Some(ref name) => {
format!("{} {}", name, self.surname())
}
None => {
self.display_initial_surname()
}
}
}
pub fn byte_len(&self) -> usize {
let mut len = self.words
.iter()
.fold(self.words.len() - 1, |sum, ref word| sum + word.len());
if let Some(suffix) = self.suffix() {
len += 2;
len += suffix.len();
}
let extra_initials = self.initials.chars().count() - self.surname_index;
if extra_initials > 0 {
len += self.initials.len() -
self.words[0..self.surname_index]
.iter()
.fold(0, |sum, ref word| sum + word.chars().nth(0).unwrap().len_utf8());
len += 2 * extra_initials;
}
len
}
pub fn display_full(&self) -> String {
let mut result = String::with_capacity(self.byte_len());
for part in self.given_names_or_initials() {
match part {
NameWordOrInitial::Word(name, _) => {
result.push_str(name);
result.push(' ');
}
NameWordOrInitial::Initial(initial) => {
result.push(initial);
result.push_str(". ");
}
}
}
let surnames = self.surnames();
if surnames.len() > 1 {
for word in surnames[0..surnames.len() - 1].iter() {
result.push_str(word);
result.push(' ');
}
}
result.push_str(&surnames[surnames.len() - 1]);
if let Some(suffix) = self.suffix() {
result.push_str(", ");
result.push_str(suffix);
}
result
}
pub fn surname_hash<H: Hasher>(&self, state: &mut H) {
let surname_chars = self.surnames()
.iter()
.flat_map(|w| w.chars())
.flat_map(transliterate)
.rev();
for c in surname_chars.filter_map(lowercase_if_alpha)
.take(comparison::MIN_SURNAME_CHAR_MATCH) {
c.hash(state);
}
}
pub fn memoized_surname_hash(&self) -> u64 {
{
let cached = self.hash.get();
if cached.is_some() {
return cached.unwrap();
}
let mut s = SipHasher::new();
self.surname_hash(&mut s);
self.hash.set(Some(s.finish()));
}
self.memoized_surname_hash()
}
}
struct GivenNamesOrInitials<'a> {
initials: Enumerate<Chars<'a>>,
known_names: Iter<'a, String>,
known_name_indices: Peekable<Iter<'a, (usize, usize)>>,
}
#[derive(Debug)]
enum NameWordOrInitial<'a> {
Word(&'a str, usize),
Initial(char),
}
impl <'a>Iterator for GivenNamesOrInitials<'a> {
type Item = NameWordOrInitial<'a>;
fn next(&mut self) -> Option<NameWordOrInitial<'a>> {
match self.initials.next() {
Some((i, initial)) => {
let mut next_name = None;
let mut initials_for_word = 1;
if let Some(&&(j, k)) = self.known_name_indices.peek() {
if j == i {
self.known_name_indices.next();
next_name = self.known_names.next();
for _ in j + 1..k {
self.initials.next();
initials_for_word += 1;
}
}
}
if let Some(name) = next_name {
Some(NameWordOrInitial::Word(name, initials_for_word))
} else {
Some(NameWordOrInitial::Initial(initial))
}
}
None => None,
}
}
}