Name Generator 4.5.2
Culture-aware name generation for C++23
Loading...
Searching...
No Matches
namegen.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2020-2026 Diego Dasso Migotto
3
4#ifndef DASMIG_NAMEGEN_HPP
5#define DASMIG_NAMEGEN_HPP
6
7#include "core.hpp"
8#include <algorithm>
9#include <array>
10#include <cmath>
11#include <cstddef>
12#include <cstdint>
13#include <filesystem>
14#include <fstream>
15#include <functional>
16#include <iterator>
17#include <limits>
18#include <map>
19#include <optional>
20#include <ostream>
21#include <span>
22#include <stdexcept>
23#include <string>
24#include <string_view>
25#include <system_error>
26#include <tuple>
27#include <utility>
28#include <vector>
29
30#ifdef DASMIG_NAME_EMBED
31#include "namegen_data.hpp"
32#endif
33
34/// @file namegen.hpp
35/// @brief Name generator library — culture-aware name generation for C++23.
36/// @author Diego Dasso Migotto (diegomigotto at hotmail dot com)
37/// @see See doc/usage.md for the narrative tutorial.
38
39DASMIG_CORE_REQUIRE(1, 1);
40
41struct ng_test_access;
42
43namespace dasmig
44{
45
46/// @brief Culture representing a country or a broader group.
47enum class culture : std::uint8_t
48{
49 afghan,
50 albanian,
51 algerian,
52 american,
53 angolan,
54 argentinian,
55 austrian,
56 azerbaijani,
57 bahraini,
58 bangladeshi,
59 belgian,
60 bolivian,
61 botswanan,
62 brazilian,
63 british,
64 bruneian,
65 bulgarian,
66 burkinabe,
67 burundian,
68 cambodian,
69 cameroonian,
70 canadian,
71 chilean,
72 chinese,
73 colombian,
74 costarican,
75 croatian,
76 cypriot,
77 czech,
78 danish,
79 djiboutian,
80 dutch,
81 ecuadorian,
82 egyptian,
83 emirati,
84 estonian,
85 ethiopian,
86 fijian,
87 filipino,
88 finnish,
89 french,
90 georgian,
91 german,
92 ghanaian,
93 greek,
94 guatemalan,
95 haitian,
96 honduran,
97 hongkonger,
98 hungarian,
99 icelandic,
100 indian,
101 indonesian,
102 iranian,
103 iraqi,
104 irish,
105 israeli,
106 italian,
107 jamaican,
108 japanese,
109 jordanian,
110 kazakh,
111 korean,
112 kuwaiti,
113 lebanese,
114 libyan,
115 lithuanian,
116 luxembourgish,
117 macanese,
118 malaysian,
119 maldivian,
120 maltese,
121 mauritian,
122 mexican,
123 moldovan,
124 moroccan,
125 namibian,
126 nigerian,
127 norwegian,
128 omani,
129 palestinian,
130 panamanian,
131 peruvian,
132 polish,
133 portuguese,
134 puertorican,
135 qatari,
136 russian,
137 salvadoran,
138 saudi,
139 serbian,
140 singaporean,
141 slovenian,
142 southafrican,
143 spanish,
144 sudanese,
145 swedish,
146 swiss,
147 syrian,
148 taiwanese,
149 tunisian,
150 turkish,
151 turkmen,
152 uruguayan,
153 yemeni,
154 any
155};
156
157/// @brief Simple gender enum to distinguish between male and female names.
158enum class gender : std::uint8_t
159{
160 m,
161 f,
162 any
163};
164
165/// @brief The per-call choices of a generation: gender and culture.
166///
167/// Passed to ng::get_name() and ng::get_surname(). Both default to `any`
168/// (random). For a surname the gender selects a gendered surname list where
169/// the culture has one.
170///
171/// @code
172/// gen.get_name({.gender = gender::f, .culture = culture::french});
173/// @endcode
175{
176 dasmig::gender gender = dasmig::gender::any; ///< Requested gender.
177 dasmig::culture culture = dasmig::culture::any; ///< Requested culture.
178};
179
180/// @brief The order a culture writes the given and the family name in.
181enum class name_order : std::uint8_t
182{
183 given_family, ///< `John Smith`.
184 family_given ///< `Kim Minjun`.
185};
186
187/// @brief How a culture forms a patronymic from the father's given name.
188enum class patronymic_style : std::uint8_t
189{
190 none,
191 east_slavic, ///< `Ivan` gives `Ivanovich` or `Ivanovna`.
192 icelandic ///< `Jón` gives `Jónsson` or `Jónsdóttir`.
193};
194
195/// @brief Which parents' surnames a child of a two-surname culture takes,
196/// and in what order.
197enum class surname_order : std::uint8_t
198{
199 paternal_first, ///< The father's first surname, then the mother's first (Spain).
200 maternal_first ///< The mother's last surname, then the father's last (Portugal).
201};
202
203/// @brief How a culture composes a full name; see ng::convention().
204///
205/// A culture without a row in `conventions.tsv` has the default: one
206/// surname, given name first.
208{
209 name_order order = name_order::given_family; ///< Given or family name first.
210 patronymic_style patronymic = patronymic_style::none; ///< How the patronymic is formed.
211 bool family_name = true; ///< False when the patronymic replaces the family name.
212 int surnames = 1; ///< 1, or 2 for cultures with a double surname.
213 double second_surname = 1.0; ///< Chance of the second surname when `surnames` is 2.
214 surname_order inheritance = surname_order::paternal_first; ///< Which parents' surnames a child takes.
215};
216
217/// @brief The part of a full name a word is.
218enum class name_role : std::uint8_t
219{
220 given,
221 patronymic,
222 family,
223 family2 ///< The second surname of a double surname.
224};
225
226/// @brief The words of a name the caller already has; see ng::compose_name().
228{
229 dasmig::gender gender = dasmig::gender::any; ///< `m` or `f`.
230 std::wstring given; ///< The given name.
231 std::wstring patronymic; ///< The patronymic; empty for none.
232 std::vector<std::wstring> family; ///< One surname, or two; empty for none.
233};
234
235/// @brief The per-call choices of ng::get_child_name().
237{
238 dasmig::gender gender = dasmig::gender::any; ///< The child's gender; `any` draws one.
239};
240
241class ng;
242
243/// @brief Return type for name generation, holding both individual parts and
244/// the full composed string.
245///
246/// Supports implicit conversion to std::wstring, streaming via operator<<,
247/// chained appending of names and surnames, and JSON output via to_json().
248class name
249{
250 public:
251 /// @brief Retrieve the random seed used to generate this name.
252 /// @return The per-call seed for replay.
253 /// @see ng::get_name(const name_request&, std::uint64_t)
254 [[nodiscard]] std::uint64_t seed() const
255 {
256 return _signature.seed;
257 }
258
259 /// @brief The seed and the data this name was generated from.
260 /// @return The replay signature; `data` is ng::data_hash() at the time
261 /// of generation.
262 [[nodiscard]] const core::seed_signature& signature() const
263 {
264 return _signature;
265 }
266
267 /// @brief Return the individual parts (names/surnames) as a vector.
268 /// @return Vector of name parts.
269 [[nodiscard]] const std::vector<std::wstring>& parts() const
270 {
271 return _parts;
272 }
273
274 /// @brief The role of each part, in the order of parts().
275 /// @return One role per part; `given` for a forename, `family` for a surname.
276 [[nodiscard]] const std::vector<name_role>& roles() const
277 {
278 return _roles;
279 }
280
281 /// @brief Whether this name was composed by a culture's convention
282 /// (ng::get_full_name(), ng::get_child_name() or ng::get_married_name()).
283 [[nodiscard]] bool composed() const
284 {
285 return _composed;
286 }
287
288 /// @brief The given name (empty when the name has none).
289 [[nodiscard]] std::wstring given() const
290 {
291 return joined(name_role::given, name_role::given);
292 }
293
294 /// @brief The patronymic (empty when the culture has none).
295 [[nodiscard]] std::wstring patronymic() const
296 {
297 return joined(name_role::patronymic, name_role::patronymic);
298 }
299
300 /// @brief The family name; both surnames of a double surname, in order.
301 [[nodiscard]] std::wstring family() const
302 {
303 return joined(name_role::family, name_role::family2);
304 }
305
306 /// @brief Append a forename to this name, preserving gender and culture.
307 ///
308 /// The part is drawn from this name's seed and its position, so the same
309 /// seed and the same appends give the same full name.
310 /// @return `*this` for chaining.
311 /// @throws std::invalid_argument If no names are loaded for the culture
312 /// and gender.
313 name& append_name();
314
315 /// @brief Append a forename of a specific culture.
316 /// @param c Culture for the appended name.
317 /// @return `*this` for chaining.
318 /// @throws std::invalid_argument If no names are loaded for @p c.
320
321 /// @brief Append a surname to this name, preserving culture.
322 /// @return `*this` for chaining.
323 /// @throws std::invalid_argument If no surnames are loaded for the
324 /// culture.
326
327 /// @brief Append a surname of a specific culture.
328 /// @param c Culture for the appended surname.
329 /// @return `*this` for chaining.
330 /// @throws std::invalid_argument If no surnames are loaded for @p c.
332
333 /// @brief Write this name as a JSON object
334 /// `{"name":…,"parts":[…],"gender":…,"culture":…,"signature":{…}}`.
335 ///
336 /// `gender` is the gender of the forenames (for a surname, the one
337 /// append_name() would use) and `culture` the culture of the first part.
338 /// @param w Writer positioned where a value is allowed.
339 void to_json(core::json_writer& w) const;
340
341 /// @brief This name as a JSON document.
342 /// @return Compact JSON.
343 [[nodiscard]] std::string to_json() const
344 {
345 core::json_writer w;
346 to_json(w);
347 return w.str();
348 }
349
350 /// @brief Implicit conversion to std::wstring.
351 /// @return The full composed name string.
352 operator std::wstring() const // NOLINT(hicpp-explicit-conversions)
353 {
354 return _full_string;
355 }
356
357 /// @brief Implicit conversion to a vector of name parts.
358 operator std::vector<std::wstring>() const // NOLINT(hicpp-explicit-conversions)
359 {
360 return _parts;
361 }
362
363 /// @brief Stream the name to a wide output stream.
364 /// @param wos Output stream.
365 /// @param n Name to stream.
366 /// @return Reference to the output stream.
367 friend std::wostream& operator<<(std::wostream& wos, const name& n)
368 {
369 wos << n._full_string;
370 return wos;
371 }
372
373 private:
374 // Private constructor — names are created only by ng.
375 name(std::wstring name_str, gender g, culture c, const ng* owner,
376 name_role role = name_role::given)
377 : _full_string(std::move(name_str)), _gender(g), _culture(c), _owner(owner)
378 {
379 _parts.push_back(_full_string);
380 _roles.push_back(role);
381 }
382
383 void append_part(std::wstring part, name_role role)
384 {
385 _full_string.append(L" ").append(part);
386 _parts.push_back(std::move(part));
387 _roles.push_back(role);
388 }
389
390 // The parts whose role lies in [first, last], joined by spaces.
391 [[nodiscard]] std::wstring joined(name_role first, name_role last) const
392 {
393 std::wstring out;
394 for (std::size_t i = 0; i < _parts.size(); ++i)
395 {
396 if (_roles.at(i) < first || _roles.at(i) > last) continue;
397 if (!out.empty()) out.append(L" ");
398 out.append(_parts.at(i));
399 }
400 return out;
401 }
402
403 std::wstring _full_string; ///< Full composed name.
404 std::vector<std::wstring> _parts; ///< Individual name parts.
405 std::vector<name_role> _roles; ///< The role of each part.
406 bool _composed = false; ///< Composed by a convention.
407 gender _gender; ///< Gender of the forenames.
408 culture _culture; ///< Culture of the first part.
409 const ng* _owner; ///< Generator that created this name.
410 core::seed_signature _signature; ///< Seed and data hash.
411
412 friend class ng;
413};
414
415/// @brief Name generator that produces culture-aware names and surnames.
416///
417/// Generates realistic names by picking from popular name databases indexed
418/// by culture and gender, weighted by popularity. Supports 105 cultures.
419///
420/// Output is identical on every compiler and platform (dasmig-core): a seed,
421/// the same request and the same data give the same name everywhere.
422///
423/// Can be used as a singleton via instance() or constructed independently.
424/// Independent instances own their own name databases and random engine.
425///
426/// @par Thread safety
427/// Each instance is independent. Concurrent calls to get_name() on
428/// the **same** instance require external synchronization. load() and
429/// extend() mutate internal state and must not be called concurrently with
430/// get_name() on the same instance.
431class ng
432{
433 public:
434 /// @brief Default constructor — creates an empty generator with no names.
435 ///
436 /// Call load() to populate name databases before generating.
437 ng() = default;
438
439 ng(const ng&) = delete; ///< Not copyable.
440 ng& operator=(const ng&) = delete; ///< Not copyable.
441 ng(ng&&) noexcept = default; ///< Move constructor.
442 ng& operator=(ng&&) noexcept = default; ///< Move assignment.
443 ~ng() = default; ///< Default destructor.
444
445 /// @brief Access the global singleton instance.
446 ///
447 /// Loads the `lite` tier on first access (or `full` when `lite` is not
448 /// found), from compiled-in data or an auto-probed `resources/`.
449 /// For independent generators, prefer constructing a separate ng instance.
450 /// @return Reference to the global ng instance.
451 static ng& instance()
452 {
453 static ng inst{auto_probe_tag{}};
454 return inst;
455 }
456
457 /// @brief Translate an ISO 3166 2-letter country code to a culture enum.
458 /// @param country_code Two-letter country code (e.g., L"us", L"br").
459 /// @return Matching culture, or culture::any if not recognized.
460 [[nodiscard]] static culture to_culture(std::wstring_view country_code)
461 {
462 const auto code = core::to_utf8(std::wstring{country_code});
463 for (std::size_t i = 0; i < culture_codes_.size(); ++i)
464 {
465 if (culture_codes_.at(i) == code) return static_cast<culture>(i);
466 }
467 return culture::any;
468 }
469
470 /// @brief Translate a gender string to a gender enum.
471 /// @param gender_string Gender string (e.g., L"male", L"female", L"m", L"f").
472 /// @return Matching gender, or gender::any if not recognized.
473 [[nodiscard]] static gender to_gender(std::wstring_view gender_string)
474 {
475 if (gender_string == L"m" || gender_string == L"male") return gender::m;
476 if (gender_string == L"f" || gender_string == L"female") return gender::f;
477 return gender::any;
478 }
479
480 /// @brief The ISO 3166 2-letter country code of a culture.
481 /// @param c Culture.
482 /// @return Lower-case code such as `"br"`, or `""` for culture::any.
483 [[nodiscard]] static std::string_view culture_code(culture c)
484 {
485 const auto idx = static_cast<std::size_t>(c);
486 return idx < culture_codes_.size() ? culture_codes_.at(idx) : std::string_view{};
487 }
488
489 /// @brief The name of a culture.
490 /// @param c Culture.
491 /// @return Lower-case name such as `"brazilian"`, or `"any"`.
492 [[nodiscard]] static std::string_view culture_name(culture c)
493 {
494 const auto idx = static_cast<std::size_t>(c);
495 return idx < culture_names_.size() ? culture_names_.at(idx) : std::string_view{"any"};
496 }
497
498 /// @brief Generate a first name.
499 /// @param request Gender and culture (both default to `any`).
500 /// @return A name object supporting chained appending.
501 /// @throws std::invalid_argument If no names loaded for the resolved culture/gender.
502 [[nodiscard]] name get_name(const name_request& request)
503 {
504 return get_name(request, _engine());
505 }
506
507 /// @brief Generate a deterministic first name using a specific seed.
508 /// @param request Gender and culture.
509 /// @param call_seed Seed; the same seed, request and data give the same
510 /// name on every platform.
511 /// @return A name object.
512 /// @throws std::invalid_argument If no names loaded for the resolved culture/gender.
513 [[nodiscard]] name get_name(const name_request& request,
514 std::uint64_t call_seed) const
515 {
516 return solver(true, request.gender, request.culture, call_seed);
517 }
518
519 // -- Batch generation -------------------------------------------------
520
521 /// @brief Generate a batch of name results from a seed drawn like
522 /// get_name() draws its own.
523 ///
524 /// Item `i` is `get_name(request, core::item_seed(batch_seed, options.first + i))`
525 /// for the drawn batch seed; see the seeded overload.
526 ///
527 /// @param request What every item is generated from.
528 /// @param options Count, first index, threads and uniqueness.
529 /// @return The results, in index order.
530 [[nodiscard]] std::vector<name> get_name_batch(const name_request& request,
531 const core::batch_options& options)
532 {
533 return get_name_batch(request, options, _engine());
534 }
535
536 /// @brief Generate a batch of name results, deterministically.
537 ///
538 /// Item `i` is exactly `get_name(request, core::item_seed(batch_seed,
539 /// options.first + i))`, so an item replays on its own, a range can be
540 /// generated directly, two batches that follow each other equal one, and
541 /// the output does not depend on `options.threads`.
542 ///
543 /// @param request What every item is generated from.
544 /// @param options Count, first index, threads and uniqueness (see
545 /// core::unique_rule; the rule must be made for `name`).
546 /// @param batch_seed Seed of the whole batch.
547 /// @return The results, in index order.
548 /// @throws std::invalid_argument If the request or options are invalid.
549 /// @throws std::runtime_error If no data has been loaded, or a unique
550 /// batch runs out of attempts.
551 [[nodiscard]] std::vector<name> get_name_batch(const name_request& request,
552 const core::batch_options& options,
553 std::uint64_t batch_seed) const
554 {
555 return core::run_batch(options, batch_seed, [&](std::uint64_t item_seed)
556 { return get_name(request, item_seed); });
557 }
558
559 /// @brief Stream a batch of name results to a sink without holding the
560 /// whole batch.
561 ///
562 /// Generates the same items as get_name_batch() and calls
563 /// `sink(index, item)` in index order on the calling thread; `index`
564 /// includes `options.first`.
565 ///
566 /// @tparam Sink Callable taking `(std::uint64_t, name&)`; for example
567 /// core::jsonl_writer or core::csv_writer.
568 /// @param request What every item is generated from.
569 /// @param options Count, first index, threads and uniqueness.
570 /// @param batch_seed Seed of the whole batch.
571 /// @param sink Receives the items.
572 template <typename Sink>
573 void for_each_name(const name_request& request, const core::batch_options& options,
574 std::uint64_t batch_seed, Sink&& sink) const
575 {
576 core::for_each_batch(options, batch_seed,
577 [&](std::uint64_t item_seed) { return get_name(request, item_seed); },
578 std::forward<Sink>(sink));
579 }
580
581 /// @brief Stream a batch of name results with a batch seed drawn like
582 /// get_name() draws its own.
583 /// @tparam Sink Callable taking `(std::uint64_t, name&)`.
584 /// @param request What every item is generated from.
585 /// @param options Count, first index, threads and uniqueness.
586 /// @param sink Receives the items.
587 template <typename Sink>
588 void for_each_name(const name_request& request, const core::batch_options& options,
589 Sink&& sink)
590 {
591 for_each_name(request, options, _engine(), std::forward<Sink>(sink));
592 }
593
594
595 /// @brief Generate a surname.
596 /// @param request Culture, and gender for cultures with gendered surnames
597 /// (both default to `any`).
598 /// @return A name object supporting chained appending.
599 /// @throws std::invalid_argument If no surnames loaded for the resolved culture.
600 [[nodiscard]] name get_surname(const name_request& request)
601 {
602 return get_surname(request, _engine());
603 }
604
605 /// @brief Generate a deterministic surname using a specific seed.
606 /// @param request Culture and gender.
607 /// @param call_seed Seed for reproducible results.
608 /// @return A name object.
609 /// @throws std::invalid_argument If no surnames loaded for the resolved culture.
610 [[nodiscard]] name get_surname(const name_request& request,
611 std::uint64_t call_seed) const
612 {
613 return solver(false, request.gender, request.culture, call_seed);
614 }
615
616 // -- Batch generation -------------------------------------------------
617
618 /// @brief Generate a batch of surname results from a seed drawn like
619 /// get_surname() draws its own.
620 ///
621 /// Item `i` is `get_surname(request, core::item_seed(batch_seed, options.first + i))`
622 /// for the drawn batch seed; see the seeded overload.
623 ///
624 /// @param request What every item is generated from.
625 /// @param options Count, first index, threads and uniqueness.
626 /// @return The results, in index order.
627 [[nodiscard]] std::vector<name> get_surname_batch(const name_request& request,
628 const core::batch_options& options)
629 {
630 return get_surname_batch(request, options, _engine());
631 }
632
633 /// @brief Generate a batch of surname results, deterministically.
634 ///
635 /// Item `i` is exactly `get_surname(request, core::item_seed(batch_seed,
636 /// options.first + i))`, so an item replays on its own, a range can be
637 /// generated directly, two batches that follow each other equal one, and
638 /// the output does not depend on `options.threads`.
639 ///
640 /// @param request What every item is generated from.
641 /// @param options Count, first index, threads and uniqueness (see
642 /// core::unique_rule; the rule must be made for `name`).
643 /// @param batch_seed Seed of the whole batch.
644 /// @return The results, in index order.
645 /// @throws std::invalid_argument If the request or options are invalid.
646 /// @throws std::runtime_error If no data has been loaded, or a unique
647 /// batch runs out of attempts.
648 [[nodiscard]] std::vector<name> get_surname_batch(const name_request& request,
649 const core::batch_options& options,
650 std::uint64_t batch_seed) const
651 {
652 return core::run_batch(options, batch_seed, [&](std::uint64_t item_seed)
653 { return get_surname(request, item_seed); });
654 }
655
656 /// @brief Stream a batch of surname results to a sink without holding the
657 /// whole batch.
658 ///
659 /// Generates the same items as get_surname_batch() and calls
660 /// `sink(index, item)` in index order on the calling thread; `index`
661 /// includes `options.first`.
662 ///
663 /// @tparam Sink Callable taking `(std::uint64_t, name&)`; for example
664 /// core::jsonl_writer or core::csv_writer.
665 /// @param request What every item is generated from.
666 /// @param options Count, first index, threads and uniqueness.
667 /// @param batch_seed Seed of the whole batch.
668 /// @param sink Receives the items.
669 template <typename Sink>
670 void for_each_surname(const name_request& request, const core::batch_options& options,
671 std::uint64_t batch_seed, Sink&& sink) const
672 {
673 core::for_each_batch(options, batch_seed,
674 [&](std::uint64_t item_seed) { return get_surname(request, item_seed); },
675 std::forward<Sink>(sink));
676 }
677
678 /// @brief Stream a batch of surname results with a batch seed drawn like
679 /// get_surname() draws its own.
680 /// @tparam Sink Callable taking `(std::uint64_t, name&)`.
681 /// @param request What every item is generated from.
682 /// @param options Count, first index, threads and uniqueness.
683 /// @param sink Receives the items.
684 template <typename Sink>
685 void for_each_surname(const name_request& request, const core::batch_options& options,
686 Sink&& sink)
687 {
688 for_each_surname(request, options, _engine(), std::forward<Sink>(sink));
689 }
690
691
692 // -- Full names, children and marriage ------------------------------------------
693
694 /// @brief How a culture composes a full name.
695 /// @param c Culture.
696 /// @return The convention loaded from `conventions.tsv`; the default (one
697 /// surname, given name first) for a culture without a row.
698 [[nodiscard]] naming_convention convention(culture c) const
699 {
700 const auto it = _conventions.find(c);
701 return it == _conventions.end() ? naming_convention{} : it->second;
702 }
703
704 /// @brief Generate a full name by the culture's convention.
705 ///
706 /// The parts follow the culture's order: family name first for Chinese,
707 /// Japanese and Korean; two surnames for Spanish and Portuguese; a
708 /// patronymic from a drawn father's name for Russian and Icelandic. The
709 /// parts carry roles (name::roles()). get_name() and get_surname() are
710 /// unchanged by conventions.
711 ///
712 /// @param request Gender and culture (both default to `any`).
713 /// @return A composed name.
714 /// @throws std::invalid_argument If no names are loaded for the resolved
715 /// culture and gender.
716 [[nodiscard]] name get_full_name(const name_request& request)
717 {
718 return get_full_name(request, _engine());
719 }
720
721 /// @brief Generate a deterministic full name.
722 /// @param request Gender and culture.
723 /// @param call_seed Seed; the same seed, request and data give the same
724 /// name on every platform.
725 /// @return A composed name.
726 /// @throws std::invalid_argument If no names are loaded for the resolved
727 /// culture and gender.
728 [[nodiscard]] name get_full_name(const name_request& request, std::uint64_t call_seed) const
729 {
730 const core::rng r{call_seed};
731 auto rg = r.split("gender");
732 const gender g = resolve_gender(request.gender, rg);
733 auto rc = r.split("culture");
734 const culture c = resolve_composed_culture_(request.culture, g == gender::m, g == gender::f, rc);
735 return make_name_(draw_person_(g, c, r.split("person")), c, call_seed);
736 }
737
738 /// @brief Generate a batch of full names from a seed drawn like
739 /// get_full_name() draws its own.
740 /// @param request What every item is generated from.
741 /// @param options Count, first index, threads and uniqueness.
742 /// @return The results, in index order.
743 [[nodiscard]] std::vector<name> get_full_name_batch(const name_request& request,
744 const core::batch_options& options)
745 {
746 return get_full_name_batch(request, options, _engine());
747 }
748
749 /// @brief Generate a batch of full names, deterministically: item `i` is
750 /// `get_full_name(request, core::item_seed(batch_seed, options.first + i))`.
751 /// @param request What every item is generated from.
752 /// @param options Count, first index, threads and uniqueness.
753 /// @param batch_seed Seed of the whole batch.
754 /// @return The results, in index order.
755 [[nodiscard]] std::vector<name> get_full_name_batch(const name_request& request,
756 const core::batch_options& options,
757 std::uint64_t batch_seed) const
758 {
759 return core::run_batch(options, batch_seed, [&](std::uint64_t item_seed)
760 { return get_full_name(request, item_seed); });
761 }
762
763 /// @brief Stream a batch of full names to a sink, in index order.
764 /// @tparam Sink Callable taking `(std::uint64_t, name&)`.
765 /// @param request What every item is generated from.
766 /// @param options Count, first index, threads and uniqueness.
767 /// @param batch_seed Seed of the whole batch.
768 /// @param sink Receives the items.
769 template <typename Sink>
770 void for_each_full_name(const name_request& request, const core::batch_options& options,
771 std::uint64_t batch_seed, Sink&& sink) const
772 {
773 core::for_each_batch(options, batch_seed,
774 [&](std::uint64_t item_seed) { return get_full_name(request, item_seed); },
775 std::forward<Sink>(sink));
776 }
777
778 /// @brief Stream a batch of full names with a batch seed drawn like
779 /// get_full_name() draws its own.
780 /// @tparam Sink Callable taking `(std::uint64_t, name&)`.
781 /// @param request What every item is generated from.
782 /// @param options Count, first index, threads and uniqueness.
783 /// @param sink Receives the items.
784 template <typename Sink>
785 void for_each_full_name(const name_request& request, const core::batch_options& options,
786 Sink&& sink)
787 {
788 for_each_full_name(request, options, _engine(), std::forward<Sink>(sink));
789 }
790
791 /// @brief Name a child of two people by the culture's convention.
792 ///
793 /// The child takes its family name from the parents as the culture
794 /// does: one surname cultures give the father's family name (a
795 /// daughter its female form where the culture has one); two-surname
796 /// cultures give one surname of each parent, in the culture's
797 /// surname_order; patronymic cultures derive the patronymic from the
798 /// father's given name. The given name is drawn from the father's
799 /// culture. Only the parts' roles are read, so the parents can be any
800 /// names (composed or not); the structure of a family (who the
801 /// parents are, how many children) is the caller's.
802 ///
803 /// Siblings are not made distinct: draw each with its own seed and
804 /// compare, if that matters.
805 ///
806 /// @param father The father's name; its culture is the child's.
807 /// @param mother The mother's name.
808 /// @param request The child's gender.
809 /// @return A composed name.
810 /// @throws std::invalid_argument If the father's culture is `any` or has
811 /// no forenames or surnames loaded.
812 [[nodiscard]] name get_child_name(const name& father, const name& mother,
813 const child_name_request& request)
814 {
815 return get_child_name(father, mother, request, _engine());
816 }
817
818 /// @brief Name a child of two people, deterministically.
819 /// @param father The father's name; its culture is the child's.
820 /// @param mother The mother's name.
821 /// @param request The child's gender.
822 /// @param call_seed Seed; the same seed, parents and data give the same
823 /// name on every platform.
824 /// @return A composed name.
825 /// @throws std::invalid_argument If the father's culture is `any` or has
826 /// no forenames or surnames loaded.
827 [[nodiscard]] name get_child_name(const name& father, const name& mother,
828 const child_name_request& request,
829 std::uint64_t call_seed) const
830 {
831 const culture c = father._culture;
832 if (c == culture::any) throw std::invalid_argument("get_child_name: the father has no culture");
833 const core::rng r{call_seed};
834 auto rg = r.split("gender");
835 const gender g = resolve_gender(request.gender, rg);
836 const auto cv = convention(c);
837 const person dad = person_of_(father);
838 const person mum = person_of_(mother);
839
840 person child{.g = g, .given = pick_forename_(g, c, r.split("given")), .patronymic = {}, .family = {}};
841 if (cv.patronymic != patronymic_style::none)
842 {
843 child.patronymic = patronymic_of_(cv.patronymic, dad.given, g == gender::f);
844 }
845 child.family = child_family_(dad, mum, g, c, cv);
846 return make_name_(child, c, call_seed);
847 }
848
849 /// @brief The name a woman has after marrying, by the culture's convention.
850 ///
851 /// A single-surname culture gives her the husband's family name, in its
852 /// married form where the culture has one (Kozlov gives Kozlova); a
853 /// two-surname or patronymic culture leaves her name as it is. Only the
854 /// roles of the names are read.
855 ///
856 /// @param wife The woman's name.
857 /// @param husband The husband's name; its culture is the one used.
858 /// @return A composed name with the wife's seed.
859 [[nodiscard]] name get_married_name(const name& wife, const name& husband) const
860 {
861 const culture c = husband._culture;
862 person p = person_of_(wife);
863 const person other = person_of_(husband);
864 const auto cv = convention(c);
865 if (c != culture::any && cv.family_name && cv.surnames == 1 && !other.family.empty())
866 {
867 p.family = {feminize_(other.family.front(), c, true)};
868 }
869 return make_name_(p, wife._culture, wife.seed());
870 }
871
872 /// @brief A name made from words the caller already has, put in the
873 /// culture's order and carrying the roles of its parts.
874 ///
875 /// For a person whose name is known and whose relatives are to be named
876 /// to match: pass the result to get_child_name(), get_parent_name() or
877 /// get_married_name(), which read only the roles of the parts.
878 ///
879 /// @param parts The words of the name.
880 /// @param c The culture whose convention orders them; not `any`.
881 /// @param call_seed Seed recorded in the name's signature.
882 /// @return A composed name.
883 /// @throws std::invalid_argument If the culture is `any`, the gender is not
884 /// male or female, or the given name is empty.
885 [[nodiscard]] name compose_name(const name_parts& parts, culture c, std::uint64_t call_seed = 0) const
886 {
887 if (c == culture::any) throw std::invalid_argument("compose_name: the culture must not be any");
888 if (parts.gender != gender::m && parts.gender != gender::f)
889 {
890 throw std::invalid_argument("compose_name: the gender must be male or female");
891 }
892 if (parts.given.empty()) throw std::invalid_argument("compose_name: the given name is empty");
893 const person p{.g = parts.gender, .given = parts.given, .patronymic = parts.patronymic,
894 .family = parts.family};
895 return make_name_(p, c, call_seed);
896 }
897
898 /// @brief Name a parent of an existing person, consistently with the
899 /// person's name; the inverse of get_child_name().
900 ///
901 /// The father's family name is the child's (in its male form where the
902 /// culture has one), and in a patronymic culture his given name is one
903 /// whose patronymic is the child's. Two-surname cultures give the
904 /// surname the child took from this parent, in the slot the culture
905 /// puts it. Everything the child's name does not fix (the mother's
906 /// family name, the other surname of a parent, a grandparent's name in
907 /// a patronymic) is drawn. The culture is the child's. Only the roles
908 /// of the child's parts are read.
909 ///
910 /// @param child The person's name; its culture is the parent's.
911 /// @param parent_gender `gender::m` or `gender::f`.
912 /// @return A composed name.
913 /// @throws std::invalid_argument If the child's culture is `any`, the
914 /// gender is `any`, or the culture has no names loaded.
915 [[nodiscard]] name get_parent_name(const name& child, gender parent_gender)
916 {
917 return get_parent_name(child, parent_gender, _engine());
918 }
919
920 /// @brief Name a parent of an existing person, deterministically.
921 /// @param child The person's name; its culture is the parent's.
922 /// @param parent_gender `gender::m` or `gender::f`.
923 /// @param call_seed Seed; the same seed, child and data give the same
924 /// name on every platform.
925 /// @return A composed name.
926 /// @throws std::invalid_argument If the child's culture is `any`, the
927 /// gender is `any`, or the culture has no names loaded.
928 [[nodiscard]] name get_parent_name(const name& child, gender parent_gender,
929 std::uint64_t call_seed) const
930 {
931 const culture c = child._culture;
932 if (c == culture::any) throw std::invalid_argument("get_parent_name: the child has no culture");
933 if (parent_gender != gender::m && parent_gender != gender::f)
934 {
935 throw std::invalid_argument("get_parent_name: the parent's gender must be male or female");
936 }
937 const core::rng r{call_seed};
938 const auto cv = convention(c);
939 const person kid = person_of_(child);
940 const bool father = parent_gender == gender::m;
941 person p = draw_person_(parent_gender, c, r.split("person"));
942
943 if (father && cv.patronymic != patronymic_style::none && !kid.patronymic.empty())
944 {
945 p.given = father_given_(cv.patronymic, kid, c, p.given, r.split("given"));
946 }
947 if (cv.family_name && !kid.family.empty())
948 {
949 if (cv.surnames == 2 && kid.family.size() == 2)
950 {
951 // The inverse of child_family_(): which of the child's surnames
952 // came from this parent, and the slot it sits in.
953 const bool paternal = cv.inheritance == surname_order::paternal_first;
954 const auto& inherited = kid.family.at(father == paternal ? 0 : 1);
955 if (p.family.size() < 2) p.family.push_back(pick_surname_(parent_gender, c, r.split("family2")));
956 const std::size_t kept = paternal ? 0 : 1;
957 // The surname the parent was not given by the child must differ
958 // from the inherited one when it can, as in draw_person_().
959 if (p.family.at(1 - kept) == inherited)
960 {
961 const auto rf = r.split("family3");
962 for (std::size_t attempt = 0; attempt < 8 && p.family.at(1 - kept) == inherited; ++attempt)
963 {
964 p.family.at(1 - kept) = pick_surname_(parent_gender, c, rf.split(attempt));
965 }
966 }
967 p.family.at(kept) = inherited;
968 }
969 else if (father)
970 {
971 p.family = {masculine_(kid.family.back(), c)};
972 }
973 else if (cv.surnames == 2)
974 {
975 p.family.resize(1); // a child with one surname had parents with one
976 }
977 }
978 return make_name_(p, c, call_seed);
979 }
980
981 /// @brief The patronymic a father's given name gives a child.
982 ///
983 /// Rule-based, for names in Latin script, with a short list of irregular
984 /// names (Pavel to Pavlovich, Jón to Jónsson).
985 /// @param style The culture's patronymic style.
986 /// @param father The father's given name.
987 /// @param daughter Whether the child is a daughter.
988 /// @return The patronymic; empty for patronymic_style::none.
989 [[nodiscard]] static std::wstring patronymic_of(patronymic_style style, const std::wstring& father,
990 bool daughter)
991 {
992 return patronymic_of_(style, father, daughter);
993 }
994
995 /// @brief The female form of a male surname, by the culture's
996 /// `surname_forms.tsv` rules.
997 /// @param surname A male surname.
998 /// @param c Culture.
999 /// @param married Whether to give the form a wife takes rather than the
1000 /// one a daughter has (they differ in Lithuanian).
1001 /// @return The form; @p surname when the culture has no rule for it.
1002 [[nodiscard]] std::wstring female_form(const std::wstring& surname, culture c,
1003 bool married = false) const
1004 {
1005 return feminize_(surname, c, married);
1006 }
1007
1008 /// @brief The layers in effect for `conventions.tsv`.
1009 /// @return The layer records.
1010 [[nodiscard]] const std::vector<core::layer_info>& convention_layers() const
1011 {
1012 return _convention_table.layers();
1013 }
1014
1015 /// @brief The layers in effect for `surname_forms.tsv`.
1016 /// @return The layer records.
1017 [[nodiscard]] const std::vector<core::layer_info>& surname_form_layers() const
1018 {
1019 return _form_table.layers();
1020 }
1021
1022 /// @brief Check whether any name databases have been loaded.
1023 /// @return `true` if at least one name list is loaded.
1024 [[nodiscard]] bool has_resources() const
1025 {
1026 return !_m_pool.empty() || !_f_pool.empty() || !_sur_pool.empty();
1027 }
1028
1029 /// @brief Load name files from a directory, replacing all names and
1030 /// layers loaded before.
1031 ///
1032 /// Reads every `.names` file below @p resource_path, in path order (see
1033 /// doc/usage.md for the format). A path that is not a directory is
1034 /// ignored.
1035 ///
1036 /// @param resource_path Directory containing `.names` files, such as
1037 /// `resources/lite`.
1038 /// @throws core::tsv_error If a file is malformed; the names are then
1039 /// unchanged.
1040 void load(const std::filesystem::path& resource_path)
1041 {
1042 std::error_code ec;
1043 if (!std::filesystem::is_directory(resource_path, ec)) return;
1044 apply_(read_directory_(resource_path), core::layer_mode::replace, true);
1045 }
1046
1047 /// @brief Load a dataset tier, replacing all names and layers loaded
1048 /// before.
1049 ///
1050 /// `lite` uses the compiled-in copy when built with `DASMIG_NAME_EMBED`.
1051 /// Otherwise the tier is read from the first of `resources`,
1052 /// `../resources`, `name-generator/resources` and
1053 /// `../name-generator/resources` that has it.
1054 ///
1055 /// @param tier The dataset size to load (dataset::lite or dataset::full).
1056 /// @return `true` if the tier was found and loaded.
1057 /// @throws core::tsv_error If a file is malformed.
1058 [[nodiscard]] bool load(dataset tier)
1059 {
1060 const std::string tier_dir{core::tier_name(tier)};
1061 data_bundle bundle;
1062 for (const auto& file : embedded_files_())
1063 {
1064 if (!file.path.starts_with(tier_dir + "/")) continue;
1065 const std::string source = "embedded:" + std::string{file.path};
1066 if (file.path.ends_with(".names"))
1067 {
1068 bundle.names.push_back(parse_names_(file.text(), source));
1069 }
1070 else if (file.path == tier_dir + "/" + std::string{conventions_file_})
1071 {
1072 bundle.conventions = core::tsv_document::parse(file.text(), source);
1073 }
1074 else if (file.path == tier_dir + "/" + std::string{forms_file_})
1075 {
1076 bundle.forms = core::tsv_document::parse(file.text(), source);
1077 }
1078 }
1079 if (bundle.names.empty())
1080 {
1081 const auto root = core::find_resources(library_name_, tier_dir + "/" + std::string{marker_file_});
1082 if (!root) return false;
1083 bundle = read_directory_(*root / tier_dir);
1084 }
1085 if (bundle.names.empty()) return false;
1086 apply_(std::move(bundle), core::layer_mode::replace, true);
1087 return true;
1088 }
1089
1090 /// @brief Add name layers from a `.names` file or a directory of them.
1091 ///
1092 /// Each file names its culture and gender in its first two lines, so it
1093 /// adds to (or changes, or removes from) that list. A directory is
1094 /// applied all together, or not at all if any file is invalid.
1095 ///
1096 /// @param path A `.names` file or a directory.
1097 /// @param mode How the layers combine with the names loaded before.
1098 /// @throws core::tsv_error If a file cannot be read or is invalid; the
1099 /// names are then unchanged.
1100 /// @throws std::invalid_argument If @p path is a file without the
1101 /// `.names` extension.
1102 void extend(const std::filesystem::path& path,
1103 core::layer_mode mode = core::layer_mode::override)
1104 {
1105 std::error_code ec;
1106 if (std::filesystem::is_directory(path, ec))
1107 {
1108 apply_(read_directory_(path), mode, false);
1109 return;
1110 }
1111 if (path.filename() == conventions_file_ || path.filename() == forms_file_)
1112 {
1113 data_bundle bundle;
1114 auto doc = core::tsv_document::parse(read_text_(path), path.string());
1115 (path.filename() == conventions_file_ ? bundle.conventions : bundle.forms) = std::move(doc);
1116 apply_(std::move(bundle), mode, false);
1117 return;
1118 }
1119 if (path.extension() != ".names")
1120 {
1121 throw std::invalid_argument("extend: expected a .names, conventions.tsv or "
1122 "surname_forms.tsv file, got " +
1123 path.filename().string());
1124 }
1125 data_bundle bundle;
1126 bundle.names.push_back(read_file_(path));
1127 apply_(std::move(bundle), mode, false);
1128 }
1129
1130 /// @brief Add a layer of `conventions.tsv` from text.
1131 /// @param text Tab-separated text with a header line: `culture` (a
1132 /// culture name such as `russian`, the key) and any of `order`
1133 /// (`given_family`, `family_given`), `patronymic` (`none`,
1134 /// `east_slavic`, `icelandic`), `family_name` (0 or 1),
1135 /// `surnames` (1 or 2), `second_surname` (a chance from 0 to 1)
1136 /// and `surname_order` (`paternal_first`, `maternal_first`).
1137 /// @param source Name used in errors.
1138 /// @param mode How the layer combines with the conventions loaded before.
1139 /// @return What the layer did.
1140 /// @throws core::tsv_error If the text is invalid; nothing then changes.
1141 const core::layer_info& extend_conventions_from_string(
1142 std::string_view text, std::string source,
1143 core::layer_mode mode = core::layer_mode::override)
1144 {
1145 data_bundle bundle;
1146 bundle.conventions = core::tsv_document::parse(text, std::move(source));
1147 apply_(std::move(bundle), mode, false);
1148 return _convention_table.layers().back();
1149 }
1150
1151 /// @brief Add a layer of `surname_forms.tsv` from text.
1152 /// @param text Tab-separated text with a header line: `culture` and
1153 /// `male` (the keys: the ending of a male surname, or `*` for
1154 /// any), `female` (the ending a daughter has instead) and
1155 /// optionally `married` (the ending a wife has; `female` when
1156 /// empty). The longest matching `male` ending applies.
1157 /// @param source Name used in errors.
1158 /// @param mode How the layer combines with the rules loaded before.
1159 /// @return What the layer did.
1160 /// @throws core::tsv_error If the text is invalid; nothing then changes.
1161 const core::layer_info& extend_surname_forms_from_string(
1162 std::string_view text, std::string source,
1163 core::layer_mode mode = core::layer_mode::override)
1164 {
1165 data_bundle bundle;
1166 bundle.forms = core::tsv_document::parse(text, std::move(source));
1167 apply_(std::move(bundle), mode, false);
1168 return _form_table.layers().back();
1169 }
1170
1171 /// @brief Add a name layer from text in the `.names` format.
1172 /// @param text The country code, the list (`male`, `female` or `any`
1173 /// for surnames; `male-surname` or `female-surname` for the
1174 /// surnames of one gender), then one name per line with an
1175 /// optional weight.
1176 /// @param source Name used in errors.
1177 /// @param mode How the layer combines with the names loaded before.
1178 /// @return What the layer did.
1179 /// @throws core::tsv_error If the text is invalid; the names are then
1180 /// unchanged.
1181 const core::layer_info& extend_from_string(std::string_view text, std::string source,
1182 core::layer_mode mode = core::layer_mode::override)
1183 {
1184 data_bundle bundle;
1185 bundle.names.push_back(parse_names_(std::string{text}, std::move(source)));
1186 const auto list = bundle.names.front().list;
1187 const auto c = bundle.names.front().c;
1188 apply_(std::move(bundle), mode, false);
1189 return _tables.at(list).at(c).layers().back();
1190 }
1191
1192 /// @brief The layers in effect for one name list.
1193 /// @param c Culture.
1194 /// @param g gender::m or gender::f for forenames, gender::any for
1195 /// surnames.
1196 /// @return The layer records.
1197 /// @throws std::out_of_range If that list was never loaded.
1198 [[nodiscard]] const std::vector<core::layer_info>& layers(culture c, gender g) const
1199 {
1200 return _tables.at(list_of_(g)).at(c).layers();
1201 }
1202
1203 /// @brief The layers in effect for the surnames of one gender.
1204 /// @param c Culture.
1205 /// @param g gender::m or gender::f; gender::any is the surname list
1206 /// shared by both.
1207 /// @return The layer records.
1208 /// @throws std::out_of_range If that list was never loaded (a culture
1209 /// has one only when its surnames change with gender).
1210 [[nodiscard]] const std::vector<core::layer_info>& surname_layers(culture c, gender g) const
1211 {
1212 const auto list = g == gender::m ? male_surname_list
1213 : g == gender::f ? female_surname_list
1214 : surname_list;
1215 return _tables.at(list).at(c).layers();
1216 }
1217
1218 /// @brief Hash of the loaded names, recorded in each result's
1219 /// signature().
1220 /// @return The hash; 0 when nothing is loaded.
1221 [[nodiscard]] std::uint64_t data_hash() const { return _data_hash; }
1222
1223 private:
1224 static constexpr std::string_view library_name_ = "name-generator";
1225 static constexpr std::string_view marker_file_ = "american/male.names";
1226 static constexpr std::string_view conventions_file_ = "conventions.tsv";
1227 static constexpr std::string_view forms_file_ = "surname_forms.tsv";
1228
1229 // Indexed by culture.
1230 static constexpr std::array<std::string_view, 105> culture_codes_{
1231 "af", "al", "dz", "us", "ao", "ar", "at", "az", "bh", "bd", "be", "bo", "bw", "br", "gb",
1232 "bn", "bg", "bf", "bi", "kh", "cm", "ca", "cl", "cn", "co", "cr", "hr", "cy", "cz", "dk",
1233 "dj", "nl", "ec", "eg", "ae", "ee", "et", "fj", "ph", "fi", "fr", "ge", "de", "gh", "gr",
1234 "gt", "ht", "hn", "hk", "hu", "is", "in", "id", "ir", "iq", "ie", "il", "it", "jm", "jp",
1235 "jo", "kz", "kr", "kw", "lb", "ly", "lt", "lu", "mo", "my", "mv", "mt", "mu", "mx", "md",
1236 "ma", "na", "ng", "no", "om", "ps", "pa", "pe", "pl", "pt", "pr", "qa", "ru", "sv", "sa",
1237 "rs", "sg", "si", "za", "es", "sd", "se", "ch", "sy", "tw", "tn", "tr", "tm", "uy", "ye"};
1238
1239 static constexpr std::array<std::string_view, 105> culture_names_{
1240 "afghan", "albanian", "algerian", "american", "angolan",
1241 "argentinian", "austrian", "azerbaijani", "bahraini", "bangladeshi",
1242 "belgian", "bolivian", "botswanan", "brazilian", "british",
1243 "bruneian", "bulgarian", "burkinabe", "burundian", "cambodian",
1244 "cameroonian", "canadian", "chilean", "chinese", "colombian",
1245 "costarican", "croatian", "cypriot", "czech", "danish",
1246 "djiboutian", "dutch", "ecuadorian", "egyptian", "emirati",
1247 "estonian", "ethiopian", "fijian", "filipino", "finnish",
1248 "french", "georgian", "german", "ghanaian", "greek",
1249 "guatemalan", "haitian", "honduran", "hongkonger", "hungarian",
1250 "icelandic", "indian", "indonesian", "iranian", "iraqi",
1251 "irish", "israeli", "italian", "jamaican", "japanese",
1252 "jordanian", "kazakh", "korean", "kuwaiti", "lebanese",
1253 "libyan", "lithuanian", "luxembourgish", "macanese", "malaysian",
1254 "maldivian", "maltese", "mauritian", "mexican", "moldovan",
1255 "moroccan", "namibian", "nigerian", "norwegian", "omani",
1256 "palestinian", "panamanian", "peruvian", "polish", "portuguese",
1257 "puertorican", "qatari", "russian", "salvadoran", "saudi",
1258 "serbian", "singaporean", "slovenian", "southafrican", "spanish",
1259 "sudanese", "swedish", "swiss", "syrian", "taiwanese",
1260 "tunisian", "turkish", "turkmen", "uruguayan", "yemeni"};
1261
1262 static_assert(culture_codes_.size() == static_cast<std::size_t>(culture::any));
1263 static_assert(culture_names_.size() == static_cast<std::size_t>(culture::any));
1264
1265 // The kinds of name list, as indices into _tables. The gendered surname
1266 // lists exist only for cultures whose surnames change with gender; the
1267 // others fall back to surname_list.
1268 using list_kind = std::size_t;
1269 static constexpr list_kind male_list = 0;
1270 static constexpr list_kind female_list = 1;
1271 static constexpr list_kind surname_list = 2;
1272 static constexpr list_kind male_surname_list = 3;
1273 static constexpr list_kind female_surname_list = 4;
1274 static constexpr std::size_t list_count = 5;
1275
1276 // Names of one list, ready for drawing. The names lie one after the
1277 // other in a single buffer: a string each would cost 32 bytes and often
1278 // an allocation on top of the name.
1279 struct name_pool
1280 {
1281 std::wstring text; // every name, in order
1282 std::vector<std::uint32_t> ends; // where each name ends in text
1283 core::discrete dist{1.0};
1284
1285 [[nodiscard]] bool empty() const noexcept { return ends.empty(); }
1286
1287 // Every name, as strings (the tests compare against them).
1288 [[nodiscard]] std::vector<std::wstring> names() const
1289 {
1290 std::vector<std::wstring> out;
1291 out.reserve(ends.size());
1292 for (std::size_t i = 0; i < ends.size(); ++i) out.push_back(at(i));
1293 return out;
1294 }
1295
1296 [[nodiscard]] bool contains(std::wstring_view name) const
1297 {
1298 std::size_t first = 0;
1299 for (const std::uint32_t end : ends)
1300 {
1301 if (std::wstring_view{text}.substr(first, end - first) == name) return true;
1302 first = end;
1303 }
1304 return false;
1305 }
1306
1307 // The name at @p i; throws std::out_of_range past the last.
1308 [[nodiscard]] std::wstring at(std::size_t i) const
1309 {
1310 const std::size_t end = ends.at(i);
1311 const std::size_t first = i == 0 ? 0 : ends[i - 1];
1312 return text.substr(first, end - first);
1313 }
1314 };
1315
1316 // The hash data_hash() returns: every table's layers, by list and culture.
1317 [[nodiscard]] static std::uint64_t hash_of_(
1318 const std::array<std::map<culture, core::layered_table>, list_count>& tables)
1319 {
1320 std::uint64_t h = 0;
1321 for (std::size_t list = 0; list < tables.size(); ++list)
1322 {
1323 for (const auto& [c, table] : tables.at(list))
1324 {
1325 h = core::hash_combine(h, (list << 8U) | static_cast<std::uint64_t>(c));
1326 h = core::hash_combine(h, table.data_hash());
1327 }
1328 }
1329 return h;
1330 }
1331
1332 // One parsed .names file.
1333 struct names_file
1334 {
1335 culture c;
1336 list_kind list;
1337 core::tsv_document doc;
1338 };
1339
1340 // What a data directory holds: name lists, and the two convention tables.
1341 struct data_bundle
1342 {
1343 std::vector<names_file> names;
1344 std::optional<core::tsv_document> conventions;
1345 std::optional<core::tsv_document> forms;
1346 };
1347
1348 // One rule of surname_forms.tsv: a male ending and what replaces it.
1349 struct form_rule
1350 {
1351 std::wstring male; // empty for `*`: nothing is removed
1352 std::wstring female;
1353 std::wstring married;
1354 };
1355
1356 // Layered data per list kind and culture, and the pools built from it.
1357 std::array<std::map<culture, core::layered_table>, list_count> _tables;
1358 std::uint64_t _data_hash{0}; // hash_of_(_tables), kept with it: every result needs it
1359 std::map<culture, name_pool> _m_pool;
1360 std::map<culture, name_pool> _f_pool;
1361 std::map<culture, name_pool> _sur_pool;
1362 std::map<culture, name_pool> _m_sur_pool;
1363 std::map<culture, name_pool> _f_sur_pool;
1364 core::layered_table _convention_table{convention_schema_()};
1365 core::layered_table _form_table{form_schema_()};
1366 std::map<culture, naming_convention> _conventions;
1367 std::map<culture, std::vector<form_rule>> _forms;
1368 std::uint64_t _convention_hash{0};
1369
1370 // Per-instance random engine for seed drawing.
1371 core::rng _engine{core::rng::from_entropy()};
1372
1373 // Tag type for the auto-probing singleton constructor.
1374 struct auto_probe_tag {};
1375
1376 // Singleton constructor: loads lite, or full when lite is not found.
1377 explicit ng(auto_probe_tag /*tag*/)
1378 {
1379 if (!load(dataset::lite)) (void)load(dataset::full);
1380 }
1381
1382 static std::span<const core::embedded_file> embedded_files_()
1383 {
1384#ifdef DASMIG_NAME_EMBED
1385 return embedded::namegen::files;
1386#else
1387 return {};
1388#endif
1389 }
1390
1391 [[nodiscard]] static constexpr list_kind list_of_(gender g)
1392 {
1393 switch (g)
1394 {
1395 case gender::m: return male_list;
1396 case gender::f: return female_list;
1397 case gender::any: return surname_list;
1398 }
1399 return surname_list;
1400 }
1401
1402 [[nodiscard]] const std::map<culture, name_pool>& pools_(list_kind list) const
1403 {
1404 if (list == male_list) return _m_pool;
1405 if (list == female_list) return _f_pool;
1406 if (list == male_surname_list) return _m_sur_pool;
1407 if (list == female_surname_list) return _f_sur_pool;
1408 return _sur_pool;
1409 }
1410
1411 // -- Data ---------------------------------------------------------------
1412
1413 static core::table_schema schema_()
1414 {
1415 return {.key = {"name"}, .required = {}, .optional = {"weight"}};
1416 }
1417
1418 // A row's weight: 1 when the cell is empty, otherwise a positive number.
1419 static double weight_of_(const core::tsv_row& row)
1420 {
1421 const auto w = row.get_or<double>("weight", 1.0);
1422 if (!(w > 0.0)) throw row.error("weight", "must be positive");
1423 return w;
1424 }
1425
1426 // Parse the .names format: the country code and the gender on the first
1427 // two lines, then `name<TAB>weight` rows. The two header lines are kept
1428 // as comments, so errors give the file's own line numbers.
1429 static names_file parse_names_(std::string text, std::string source)
1430 {
1431 if (text.starts_with("\xEF\xBB\xBF")) text.erase(0, 3);
1432 // A header line's text and where the next line starts; the gender
1433 // line may end the file.
1434 auto header_line = [&](std::size_t from, std::size_t line) {
1435 auto end = text.find('\n', from);
1436 if (end == std::string::npos)
1437 {
1438 if (line == 1 || from >= text.size())
1439 {
1440 throw core::tsv_error{source, line, "", "expected a country code and a gender line"};
1441 }
1442 end = text.size();
1443 }
1444 auto value = std::string_view{text}.substr(from, end - from);
1445 if (value.ends_with('\r')) value.remove_suffix(1);
1446 return std::pair{std::string{value}, std::min(end + 1, text.size())};
1447 };
1448 const auto [code, after_code] = header_line(0, 1);
1449 const auto [gender_text, after_gender] = header_line(after_code, 2);
1450 (void)after_gender;
1451
1452 const auto c = to_culture(core::from_utf8(code));
1453 if (c == culture::any)
1454 {
1455 throw core::tsv_error{source, 1, "", "unknown country code '" + code + "'"};
1456 }
1457 list_kind list = surname_list;
1458 if (gender_text == "male" || gender_text == "m")
1459 {
1460 list = male_list;
1461 }
1462 else if (gender_text == "female" || gender_text == "f")
1463 {
1464 list = female_list;
1465 }
1466 else if (gender_text == "male-surname")
1467 {
1468 list = male_surname_list;
1469 }
1470 else if (gender_text == "female-surname")
1471 {
1472 list = female_surname_list;
1473 }
1474 else if (gender_text != "any")
1475 {
1476 throw core::tsv_error{source, 2, "",
1477 "expected male, female, any, male-surname or female-surname, got '" +
1478 gender_text + "'"};
1479 }
1480
1481 text.insert(after_code, "#");
1482 text.insert(0, "#");
1483 return {.c = c, .list = list,
1484 .doc = core::tsv_document::parse(text, std::move(source), {"name", "weight", "disabled"})};
1485 }
1486
1487 static names_file read_file_(const std::filesystem::path& file)
1488 {
1489 return parse_names_(read_text_(file), file.string());
1490 }
1491
1492 static std::string read_text_(const std::filesystem::path& file)
1493 {
1494 std::ifstream in{file, std::ios::binary};
1495 if (!in) throw core::tsv_error{file.string(), 0, "", "cannot open file"};
1496 in.seekg(0, std::ios::end);
1497 const auto size = in.tellg();
1498 std::string text(size > 0 ? static_cast<std::size_t>(size) : 0, '\0');
1499 in.seekg(0, std::ios::beg);
1500 in.read(text.data(), static_cast<std::streamsize>(text.size()));
1501 text.resize(static_cast<std::size_t>(in.gcount()));
1502 return text;
1503 }
1504
1505 static data_bundle read_directory_(const std::filesystem::path& dir)
1506 {
1507 std::vector<std::filesystem::path> paths;
1508 for (const auto& entry : std::filesystem::recursive_directory_iterator(dir))
1509 {
1510 if (entry.is_regular_file() && entry.path().extension() == ".names")
1511 {
1512 paths.push_back(entry.path());
1513 }
1514 }
1515 std::ranges::sort(paths); // the iteration order is unspecified
1516 data_bundle bundle;
1517 bundle.names.reserve(paths.size());
1518 for (const auto& path : paths) bundle.names.push_back(read_file_(path));
1519 std::error_code ec;
1520 if (const auto file = dir / conventions_file_; std::filesystem::is_regular_file(file, ec))
1521 {
1522 bundle.conventions = core::tsv_document::parse(read_text_(file), file.string());
1523 }
1524 if (const auto file = dir / forms_file_; std::filesystem::is_regular_file(file, ec))
1525 {
1526 bundle.forms = core::tsv_document::parse(read_text_(file), file.string());
1527 }
1528 return bundle;
1529 }
1530
1531 // The lookup maps and the hash of the convention tables.
1532 void rebuild_conventions_()
1533 {
1534 _conventions.clear();
1535 for (const auto& row : _convention_table.rows())
1536 {
1537 _conventions.emplace(culture_from_name_(row["culture"]), convention_of_(row));
1538 }
1539 _forms.clear();
1540 for (const auto& row : _form_table.rows())
1541 {
1542 _forms[culture_from_name_(row["culture"])].push_back(form_of_(row));
1543 }
1544 _convention_hash = core::hash_combine(_convention_table.data_hash(), _form_table.data_hash());
1545 }
1546
1547 // Copies of the convention tables with the bundle's layers applied.
1548 [[nodiscard]] std::pair<core::layered_table, core::layered_table> extended_convention_tables_(
1549 data_bundle& bundle, core::layer_mode mode, bool reset) const
1550 {
1551 auto conventions = reset ? core::layered_table{convention_schema_()} : _convention_table;
1552 auto forms = reset ? core::layered_table{form_schema_()} : _form_table;
1553 const auto layer_mode = reset ? core::layer_mode::replace : mode;
1554 if (bundle.conventions)
1555 {
1556 (void)conventions.extend(std::move(*bundle.conventions), layer_mode,
1557 [](const core::tsv_row& row) { (void)convention_of_(row); });
1558 }
1559 if (bundle.forms)
1560 {
1561 (void)forms.extend(std::move(*bundle.forms), layer_mode,
1562 [](const core::tsv_row& row) { (void)form_of_(row); });
1563 }
1564 return {std::move(conventions), std::move(forms)};
1565 }
1566
1567 // Apply layers to copies of the affected tables, then commit: all or
1568 // nothing. With @p reset (load), every list is replaced.
1569 void apply_(data_bundle bundle, core::layer_mode mode, bool reset)
1570 {
1571 // The convention tables first, on copies: a bad one changes nothing.
1572 auto [next_conventions, next_forms] = extended_convention_tables_(bundle, mode, reset);
1573
1574 auto& files = bundle.names;
1575 auto next = reset ? decltype(_tables){} : _tables;
1576 // On reset each list's first file replaces; later files for the same
1577 // list extend it.
1578 std::array<std::map<culture, bool>, list_count> started;
1579 std::array<std::map<culture, bool>, list_count> touched;
1580 for (auto& file : files)
1581 {
1582 auto& tables = next.at(file.list);
1583 auto it = tables.try_emplace(file.c, schema_()).first;
1584 auto list_mode = mode;
1585 if (reset)
1586 {
1587 list_mode = started.at(file.list)[file.c] ? core::layer_mode::override
1588 : core::layer_mode::replace;
1589 }
1590 started.at(file.list)[file.c] = true;
1591 touched.at(file.list)[file.c] = true;
1592 (void)it->second.extend(std::move(file.doc), list_mode,
1593 [](const core::tsv_row& row) { (void)weight_of_(row); });
1594 }
1595
1596 // Rebuild the pools of the lists that changed.
1597 std::array<std::map<culture, name_pool>, list_count> pools;
1598 for (std::size_t list = 0; list < pools.size(); ++list)
1599 {
1600 if (!reset) pools.at(list) = pools_(list);
1601 for (const auto& [c, changed] : touched.at(list))
1602 {
1603 const auto& table = next.at(list).at(c);
1604 pools.at(list).erase(c);
1605 if (table.empty()) continue;
1606 name_pool pool;
1607 std::vector<double> weights;
1608 weights.reserve(table.size());
1609 pool.ends.reserve(table.size());
1610 // A name has at most as many characters as bytes.
1611 std::size_t bytes = 0;
1612 for (const auto& row : table.rows()) bytes += row["name"].size();
1613 if (bytes >= std::numeric_limits<std::uint32_t>::max())
1614 {
1615 throw std::length_error("name-generator: too many names in one list");
1616 }
1617 pool.text.reserve(bytes);
1618 for (const auto& row : table.rows())
1619 {
1620 pool.text += core::from_utf8(row["name"]);
1621 pool.ends.push_back(static_cast<std::uint32_t>(pool.text.size()));
1622 weights.push_back(weight_of_(row));
1623 }
1624 if (pool.text.capacity() - pool.text.size() > pool.text.size() / 8)
1625 {
1626 pool.text.shrink_to_fit();
1627 }
1628 pool.dist = core::discrete{weights};
1629 pools.at(list).emplace(c, std::move(pool));
1630 }
1631 }
1632
1633 _convention_table = std::move(next_conventions);
1634 _form_table = std::move(next_forms);
1635 rebuild_conventions_();
1636
1637 _tables = std::move(next);
1638 _data_hash = hash_of_(_tables);
1639 _m_pool = std::move(pools.at(male_list));
1640 _f_pool = std::move(pools.at(female_list));
1641 _sur_pool = std::move(pools.at(surname_list));
1642 _m_sur_pool = std::move(pools.at(male_surname_list));
1643 _f_sur_pool = std::move(pools.at(female_surname_list));
1644 }
1645
1646 // -- Generation ---------------------------------------------------------
1647
1648 // Resolve `any` culture to a random culture from those actually loaded.
1649 static culture resolve_culture(culture c, const std::map<culture, name_pool>& db,
1650 core::rng& engine)
1651 {
1652 if (c != culture::any) return c;
1653 if (db.empty())
1654 {
1655 throw std::invalid_argument("No names loaded for any culture");
1656 }
1657 auto it = db.begin();
1658 std::advance(it, static_cast<std::ptrdiff_t>(core::bounded(engine, db.size())));
1659 return it->first;
1660 }
1661
1662 // Resolve `any` gender to a concrete random gender.
1663 static gender resolve_gender(gender g, core::rng& engine)
1664 {
1665 if (g != gender::any) return g;
1666 return core::bernoulli(engine, 0.5) ? gender::f : gender::m;
1667 }
1668
1669 // Convert a gender enum to its display name for error messages.
1670 [[nodiscard]] static const char* gender_label(gender g)
1671 {
1672 switch (g)
1673 {
1674 case gender::m: return "male";
1675 case gender::f: return "female";
1676 case gender::any: return "any";
1677 }
1678 return "unknown";
1679 }
1680
1681 // Pick a weighted-random name/surname from the appropriate map.
1682 [[nodiscard]] static std::wstring pick(const std::map<culture, name_pool>& db,
1683 culture c, gender g, core::rng& engine)
1684 {
1685 auto it = db.find(c);
1686 if (it == db.end() || it->second.empty())
1687 {
1688 throw std::invalid_argument(
1689 std::string("No ") + gender_label(g) + " names loaded for culture '" +
1690 std::string{culture_name(c)} + "'");
1691 }
1692 const auto& pool = it->second;
1693 return pool.at(pool.dist(engine));
1694 }
1695
1696 // One forename: gender, culture and name from their own streams.
1697 [[nodiscard]] std::tuple<std::wstring, gender, culture> draw_forename_(
1698 gender g, culture c, const core::rng& r) const
1699 {
1700 auto rg = r.split("gender");
1701 const gender resolved_g = resolve_gender(g, rg);
1702 const auto& db = resolved_g == gender::f ? _f_pool : _m_pool;
1703 auto rc = r.split("culture");
1704 const culture resolved_c = resolve_culture(c, db, rc);
1705 auto rn = r.split("name");
1706 return {pick(db, resolved_c, resolved_g, rn), resolved_g, resolved_c};
1707 }
1708
1709 // One surname: culture and name from their own streams. A culture with
1710 // a surname list for the gender draws from it, the others from the list
1711 // shared by both.
1712 [[nodiscard]] std::pair<std::wstring, culture> draw_surname_(gender g, culture c,
1713 const core::rng& r) const
1714 {
1715 auto rc = r.split("culture");
1716 const culture resolved_c = resolve_culture(c, _sur_pool, rc);
1717 auto rn = r.split("name");
1718 const auto& gendered = g == gender::f ? _f_sur_pool : _m_sur_pool;
1719 const auto& db = gendered.contains(resolved_c) ? gendered : _sur_pool;
1720 return {pick(db, resolved_c, gender::any, rn), resolved_c};
1721 }
1722
1723 // -- Conventions and composing names -------------------------------
1724
1725 static core::table_schema convention_schema_()
1726 {
1727 return {.key = {"culture"},
1728 .required = {},
1729 .optional = {"order", "patronymic", "family_name", "surnames", "second_surname",
1730 "surname_order"}};
1731 }
1732
1733 static core::table_schema form_schema_()
1734 {
1735 return {.key = {"culture", "male"}, .required = {"female"}, .optional = {"married"}};
1736 }
1737
1738 [[nodiscard]] static culture culture_from_name_(std::string_view name)
1739 {
1740 for (std::size_t i = 0; i < culture_names_.size(); ++i)
1741 {
1742 if (culture_names_.at(i) == name) return static_cast<culture>(i);
1743 }
1744 return culture::any;
1745 }
1746
1747 static void check_culture_(const core::tsv_row& row)
1748 {
1749 if (culture_from_name_(row["culture"]) == culture::any)
1750 {
1751 throw row.error("culture", "unknown culture '" + std::string{row["culture"]} + "'");
1752 }
1753 }
1754
1755 // One row of conventions.tsv, checked.
1756 static naming_convention convention_of_(const core::tsv_row& row)
1757 {
1758 check_culture_(row);
1759 naming_convention cv;
1760 const auto order = row.get_or<std::string>("order", "given_family");
1761 if (order == "family_given")
1762 {
1763 cv.order = name_order::family_given;
1764 }
1765 else if (order != "given_family")
1766 {
1767 throw row.error("order", "expected given_family or family_given, got '" + order + "'");
1768 }
1769 const auto patronymic = row.get_or<std::string>("patronymic", "none");
1770 if (patronymic == "east_slavic")
1771 {
1772 cv.patronymic = patronymic_style::east_slavic;
1773 }
1774 else if (patronymic == "icelandic")
1775 {
1776 cv.patronymic = patronymic_style::icelandic;
1777 }
1778 else if (patronymic != "none")
1779 {
1780 throw row.error("patronymic",
1781 "expected none, east_slavic or icelandic, got '" + patronymic + "'");
1782 }
1783 cv.family_name = row.get_or<bool>("family_name", true);
1784 cv.surnames = row.get_or<int>("surnames", 1);
1785 if (cv.surnames < 1 || cv.surnames > 2) throw row.error("surnames", "must be 1 or 2");
1786 cv.second_surname = row.get_or<double>("second_surname", 1.0);
1787 if (cv.second_surname < 0.0 || cv.second_surname > 1.0)
1788 {
1789 throw row.error("second_surname", "must be between 0 and 1");
1790 }
1791 const auto inheritance = row.get_or<std::string>("surname_order", "paternal_first");
1792 if (inheritance == "maternal_first")
1793 {
1794 cv.inheritance = surname_order::maternal_first;
1795 }
1796 else if (inheritance != "paternal_first")
1797 {
1798 throw row.error("surname_order",
1799 "expected paternal_first or maternal_first, got '" + inheritance + "'");
1800 }
1801 return cv;
1802 }
1803
1804 // One row of surname_forms.tsv, checked.
1805 static form_rule form_of_(const core::tsv_row& row)
1806 {
1807 check_culture_(row);
1808 if (!row.has("male")) throw row.error("male", "missing value (use * for any ending)");
1809 if (!row.has("female")) throw row.error("female", "missing value");
1810 form_rule rule;
1811 rule.male = row["male"] == "*" ? std::wstring{} : core::from_utf8(row["male"]);
1812 rule.female = core::from_utf8(row["female"]);
1813 rule.married = row.has("married") ? core::from_utf8(row["married"]) : rule.female;
1814 return rule;
1815 }
1816
1817 [[nodiscard]] std::uint64_t composed_hash_() const
1818 {
1819 return core::hash_combine(_data_hash, _convention_hash);
1820 }
1821
1822 // A culture with forenames for the genders needed and surnames, drawn
1823 // from those loaded when @p c is `any`.
1824 [[nodiscard]] culture resolve_composed_culture_(culture c, bool need_male, bool need_female,
1825 core::rng& engine) const
1826 {
1827 if (c != culture::any) return c;
1828 std::vector<culture> candidates;
1829 for (const auto& [culture_id, pool] : _sur_pool)
1830 {
1831 if (pool.empty()) continue;
1832 if (need_male && !_m_pool.contains(culture_id)) continue;
1833 if (need_female && !_f_pool.contains(culture_id)) continue;
1834 candidates.push_back(culture_id);
1835 }
1836 if (candidates.empty()) throw std::invalid_argument("No names loaded for any culture");
1837 return candidates.at(core::bounded(engine, candidates.size()));
1838 }
1839
1840 [[nodiscard]] std::wstring pick_forename_(gender g, culture c, core::rng r) const
1841 {
1842 return pick(g == gender::f ? _f_pool : _m_pool, c, g, r);
1843 }
1844
1845 // A surname from the gendered list where the culture has one.
1846 [[nodiscard]] std::wstring pick_surname_(gender g, culture c, core::rng r) const
1847 {
1848 const auto& gendered = g == gender::f ? _f_sur_pool : _m_sur_pool;
1849 return pick(gendered.contains(c) ? gendered : _sur_pool, c, gender::any, r);
1850 }
1851
1852 // The words of one person's name, before they are put in order.
1853 struct person
1854 {
1855 gender g;
1856 std::wstring given;
1857 std::wstring patronymic;
1858 std::vector<std::wstring> family; // one surname, or two
1859 };
1860
1861 [[nodiscard]] person draw_person_(gender g, culture c, const core::rng& r) const
1862 {
1863 const auto cv = convention(c);
1864 person p{.g = g, .given = pick_forename_(g, c, r.split("given")), .patronymic = {}, .family = {}};
1865 if (cv.patronymic != patronymic_style::none)
1866 {
1867 const auto father = pick_forename_(gender::m, c, r.split("father"));
1868 p.patronymic = patronymic_of_(cv.patronymic, father, g == gender::f);
1869 }
1870 if (cv.family_name)
1871 {
1872 p.family.push_back(pick_surname_(g, c, r.split("family")));
1873 auto rs = r.split("second");
1874 if (cv.surnames == 2 && core::bernoulli(rs, cv.second_surname))
1875 {
1876 // A second surname that differs from the first when it can.
1877 const auto rf = r.split("family2");
1878 std::wstring second;
1879 for (std::size_t attempt = 0; attempt < 8; ++attempt)
1880 {
1881 second = pick_surname_(g, c, rf.split(attempt));
1882 if (second != p.family.front()) break;
1883 }
1884 p.family.push_back(std::move(second));
1885 }
1886 }
1887 return p;
1888 }
1889
1890 // The words of a name, by role.
1891 [[nodiscard]] static person person_of_(const name& n)
1892 {
1893 person p{.g = n._gender, .given = n.given(), .patronymic = n.patronymic(), .family = {}};
1894 for (std::size_t i = 0; i < n._parts.size(); ++i)
1895 {
1896 if (n._roles.at(i) == name_role::family || n._roles.at(i) == name_role::family2)
1897 {
1898 p.family.push_back(n._parts.at(i));
1899 }
1900 }
1901 return p;
1902 }
1903
1904 // A person as a name: the parts in the culture's order, with their roles.
1905 [[nodiscard]] name make_name_(const person& p, culture c, std::uint64_t seed) const
1906 {
1907 const auto cv = convention(c);
1908 using part = std::pair<name_role, const std::wstring*>;
1909 std::vector<part> given_parts;
1910 given_parts.emplace_back(name_role::given, &p.given);
1911 if (!p.patronymic.empty()) given_parts.emplace_back(name_role::patronymic, &p.patronymic);
1912 std::vector<part> family_parts;
1913 family_parts.reserve(p.family.size());
1914 for (std::size_t i = 0; i < p.family.size(); ++i)
1915 {
1916 family_parts.emplace_back(i == 0 ? name_role::family : name_role::family2, &p.family.at(i));
1917 }
1918 const bool family_first = cv.order == name_order::family_given;
1919 std::vector<part> sequence = family_first ? family_parts : given_parts;
1920 const auto& rest = family_first ? given_parts : family_parts;
1921 sequence.insert(sequence.end(), rest.begin(), rest.end());
1922
1923 name result{*sequence.front().second, p.g, c, this, sequence.front().first};
1924 for (std::size_t i = 1; i < sequence.size(); ++i)
1925 {
1926 result.append_part(*sequence.at(i).second, sequence.at(i).first);
1927 }
1928 result._composed = true;
1929 result._signature = {.seed = seed, .data = composed_hash_()};
1930 return result;
1931 }
1932
1933 // The family name of a child, from the parents' names.
1934 [[nodiscard]] std::vector<std::wstring> child_family_(const person& father, const person& mother,
1935 gender g, culture c,
1936 const naming_convention& cv) const
1937 {
1938 if (!cv.family_name || father.family.empty()) return {};
1939 if (cv.surnames == 2 && (father.family.size() == 2 || mother.family.size() == 2))
1940 {
1941 const bool maternal_first = cv.inheritance == surname_order::maternal_first;
1942 auto first = maternal_first ? mother.family.back() : father.family.front();
1943 auto second = maternal_first ? father.family.back() : mother.family.front();
1944 if (first == second)
1945 {
1946 // Two parents who share a surname do not pass it on twice when the
1947 // other surname of one of them is different.
1948 const auto& of_second = maternal_first ? father.family : mother.family;
1949 const auto& of_first = maternal_first ? mother.family : father.family;
1950 const auto different = std::ranges::find_if(of_second, [&](const std::wstring& w) { return w != first; });
1951 if (different != of_second.end())
1952 {
1953 second = *different;
1954 }
1955 else if (const auto alt = std::ranges::find_if(of_first, [&](const std::wstring& w) { return w != second; });
1956 alt != of_first.end())
1957 {
1958 first = *alt;
1959 }
1960 }
1961 return {first, second};
1962 }
1963 return {g == gender::f ? feminize_(father.family.back(), c, false) : father.family.back()};
1964 }
1965
1966 // The female form of a male surname: the longest matching ending of the
1967 // culture's rules, or the surname as it is.
1968 [[nodiscard]] std::wstring feminize_(const std::wstring& surname, culture c, bool married) const
1969 {
1970 const auto it = _forms.find(c);
1971 if (it == _forms.end()) return surname;
1972 const form_rule* best = nullptr;
1973 for (const auto& rule : it->second)
1974 {
1975 if (rule.male.size() > surname.size()) continue;
1976 if (!std::wstring_view{surname}.ends_with(rule.male)) continue;
1977 if (best == nullptr || rule.male.size() > best->male.size()) best = &rule;
1978 }
1979 if (best == nullptr) return surname;
1980 return surname.substr(0, surname.size() - best->male.size()) +
1981 (married ? best->married : best->female);
1982 }
1983
1984 // The male surname a female form comes from: the longest female ending
1985 // that undoes to a surname the rules turn back into this one, or the
1986 // surname as it is.
1987 [[nodiscard]] std::wstring masculine_(const std::wstring& surname, culture c) const
1988 {
1989 const auto it = _forms.find(c);
1990 if (it == _forms.end()) return surname;
1991 std::wstring best = surname;
1992 std::size_t best_size = 0;
1993 for (const auto& rule : it->second)
1994 {
1995 if (rule.female.size() < best_size || rule.female.size() > surname.size()) continue;
1996 if (!std::wstring_view{surname}.ends_with(rule.female)) continue;
1997 auto candidate = surname.substr(0, surname.size() - rule.female.size()) + rule.male;
1998 if (feminize_(candidate, c, false) != surname) continue;
1999 best = std::move(candidate);
2000 best_size = rule.female.size();
2001 }
2002 return best;
2003 }
2004
2005 // A father's given name that gives the child's patronymic: drawn from
2006 // the male forenames that do, or `fallback` when none does.
2007 [[nodiscard]] std::wstring father_given_(patronymic_style style, const person& kid, culture c,
2008 const std::wstring& fallback, core::rng r) const
2009 {
2010 const auto it = _m_pool.find(c);
2011 if (it == _m_pool.end()) return fallback;
2012 std::vector<std::wstring> fits;
2013 for (std::size_t i = 0; i < it->second.ends.size(); ++i)
2014 {
2015 auto candidate = it->second.at(i);
2016 if (patronymic_of_(style, candidate, kid.g == gender::f) == kid.patronymic)
2017 {
2018 fits.push_back(std::move(candidate));
2019 }
2020 }
2021 if (fits.empty()) return fallback;
2022 return fits.at(core::bounded(r, fits.size()));
2023 }
2024
2025 [[nodiscard]] static bool ends_with_(const std::wstring& text, std::wstring_view ending)
2026 {
2027 return text.size() >= ending.size() &&
2028 std::wstring_view{text}.substr(text.size() - ending.size()) == ending;
2029 }
2030
2031 [[nodiscard]] static std::wstring patronymic_of_(patronymic_style style, const std::wstring& father,
2032 bool daughter)
2033 {
2034 switch (style)
2035 {
2036 case patronymic_style::east_slavic: return east_slavic_patronymic_(father, daughter);
2037 case patronymic_style::icelandic: return icelandic_patronymic_(father, daughter);
2038 case patronymic_style::none: break;
2039 }
2040 return {};
2041 }
2042
2043 // Russian-style patronymics from a transliterated father's name.
2044 [[nodiscard]] static std::wstring east_slavic_patronymic_(const std::wstring& father, bool daughter)
2045 {
2046 struct irregular
2047 {
2048 std::wstring_view name;
2049 std::wstring_view son;
2050 std::wstring_view daughter;
2051 };
2052 static constexpr std::array<irregular, 12> exceptions{{
2053 {.name = L"Pavel", .son = L"Pavlovich", .daughter = L"Pavlovna"},
2054 {.name = L"Lev", .son = L"Lvovich", .daughter = L"Lvovna"},
2055 {.name = L"Pyotr", .son = L"Petrovich", .daughter = L"Petrovna"},
2056 {.name = L"Petr", .son = L"Petrovich", .daughter = L"Petrovna"},
2057 {.name = L"Dmitry", .son = L"Dmitriyevich", .daughter = L"Dmitriyevna"},
2058 {.name = L"Igor", .son = L"Igorevich", .daughter = L"Igorevna"},
2059 {.name = L"Yakov", .son = L"Yakovlevich", .daughter = L"Yakovlevna"},
2060 {.name = L"Ilya", .son = L"Ilyich", .daughter = L"Ilyinichna"},
2061 {.name = L"Nikita", .son = L"Nikitich", .daughter = L"Nikitichna"},
2062 {.name = L"Luka", .son = L"Lukich", .daughter = L"Lukinichna"},
2063 {.name = L"Kuzma", .son = L"Kuzmich", .daughter = L"Kuzminichna"},
2064 {.name = L"Foma", .son = L"Fomich", .daughter = L"Fominichna"},
2065 }};
2066 if (father.empty()) return {};
2067 for (const auto& e : exceptions)
2068 {
2069 if (father == e.name) return std::wstring{daughter ? e.daughter : e.son};
2070 }
2071 auto stem = father;
2072 if (ends_with_(father, L"iy") || ends_with_(father, L"ey") || ends_with_(father, L"ay") ||
2073 ends_with_(father, L"oy") || ends_with_(father, L"uy"))
2074 {
2075 return stem + (daughter ? L"evna" : L"evich");
2076 }
2077 if (ends_with_(father, L"y"))
2078 {
2079 stem.pop_back();
2080 return stem + (daughter ? L"yevna" : L"yevich");
2081 }
2082 if (ends_with_(father, L"a"))
2083 {
2084 stem.pop_back();
2085 return stem + (daughter ? L"ichna" : L"ich");
2086 }
2087 for (const wchar_t vowel : std::wstring_view{L"eiou"})
2088 {
2089 if (father.back() == vowel) return stem + (daughter ? L"vna" : L"vich");
2090 }
2091 return stem + (daughter ? L"ovna" : L"ovich");
2092 }
2093
2094 // Icelandic patronymics: the father's name in the genitive, then son or
2095 // dóttir.
2096 [[nodiscard]] static std::wstring icelandic_patronymic_(const std::wstring& father, bool daughter)
2097 {
2098 auto stem = father;
2099 if (ends_with_(stem, L"ur"))
2100 {
2101 stem.resize(stem.size() - 2);
2102 stem += L"s";
2103 }
2104 else if (ends_with_(stem, L"i"))
2105 {
2106 stem.pop_back();
2107 stem += L"a";
2108 }
2109 else if (!ends_with_(stem, L"s"))
2110 {
2111 stem += L"s";
2112 }
2113 return stem + (daughter ? L"dóttir" : L"son");
2114 }
2115
2116 // Core generation logic.
2117 [[nodiscard]] name solver(bool is_name, gender requested_gender,
2118 culture requested_culture, std::uint64_t call_seed) const
2119 {
2120 const core::rng r{call_seed};
2121 name result = [&]() -> name {
2122 if (is_name)
2123 {
2124 auto [text, g, c] = draw_forename_(requested_gender, requested_culture, r);
2125 return {std::move(text), g, c, this};
2126 }
2127 // A surname still has a gender: the one append_name() uses.
2128 auto rg = r.split("gender");
2129 const gender g = resolve_gender(requested_gender, rg);
2130 auto [text, c] = draw_surname_(g, requested_culture, r);
2131 return {std::move(text), g, c, this, name_role::family};
2132 }();
2133 result._signature = {.seed = call_seed, .data = data_hash()};
2134 return result;
2135 }
2136
2137 // Parts appended to a name draw from the name's seed and the part's
2138 // position, so a seed and the same appends replay the whole name.
2139 void append_name_impl(name& n, gender g, culture c) const
2140 {
2141 const auto r = core::rng{n.seed()}.split("part").split(n._parts.size());
2142 n.append_part(std::get<0>(draw_forename_(g, c, r)), name_role::given);
2143 }
2144
2145 void append_surname_impl(name& n, culture c) const
2146 {
2147 const auto r = core::rng{n.seed()}.split("part").split(n._parts.size());
2148 n.append_part(draw_surname_(n._gender, c, r).first, name_role::family);
2149 }
2150
2151 friend class name;
2152 friend struct ::ng_test_access;
2153};
2154
2155// Out-of-line definitions for name methods that call into ng.
2157{
2158 _owner->append_name_impl(*this, _gender, _culture);
2159 return *this;
2160}
2161
2163{
2164 _owner->append_name_impl(*this, _gender, c);
2165 return *this;
2166}
2167
2169{
2170 _owner->append_surname_impl(*this, _culture);
2171 return *this;
2172}
2173
2175{
2176 _owner->append_surname_impl(*this, c);
2177 return *this;
2178}
2179
2180inline void name::to_json(core::json_writer& w) const
2181{
2182 w.begin_object().field("name", core::to_utf8(_full_string)).key("parts").begin_array();
2183 for (const auto& part : _parts) w.value(core::to_utf8(part));
2184 w.end_array();
2185 if (_composed)
2186 {
2187 static constexpr std::array<std::string_view, 4> role_names{"given", "patronymic", "family",
2188 "family2"};
2189 w.key("roles").begin_array();
2190 for (const auto role : _roles) w.value(role_names.at(static_cast<std::size_t>(role)));
2191 w.end_array();
2192 }
2193 w.field("gender", _gender == gender::f ? "female" : "male")
2194 .field("culture", ng::culture_name(_culture))
2195 .key("signature");
2196 _signature.to_json(w);
2197 w.end_object();
2198}
2199
2200} // namespace dasmig
2201
2202#endif // DASMIG_NAMEGEN_HPP
Return type for name generation, holding both individual parts and the full composed string.
Definition namegen.hpp:249
friend std::wostream & operator<<(std::wostream &wos, const name &n)
Stream the name to a wide output stream.
Definition namegen.hpp:367
name & append_surname()
Append a surname to this name, preserving culture.
Definition namegen.hpp:2168
std::wstring given() const
The given name (empty when the name has none).
Definition namegen.hpp:289
name & append_name()
Append a forename to this name, preserving gender and culture.
Definition namegen.hpp:2156
const core::seed_signature & signature() const
The seed and the data this name was generated from.
Definition namegen.hpp:262
bool composed() const
Whether this name was composed by a culture's convention (ng::get_full_name(), ng::get_child_name() o...
Definition namegen.hpp:283
std::wstring family() const
The family name; both surnames of a double surname, in order.
Definition namegen.hpp:301
std::string to_json() const
This name as a JSON document.
Definition namegen.hpp:343
std::wstring patronymic() const
The patronymic (empty when the culture has none).
Definition namegen.hpp:295
const std::vector< name_role > & roles() const
The role of each part, in the order of parts().
Definition namegen.hpp:276
const std::vector< std::wstring > & parts() const
Return the individual parts (names/surnames) as a vector.
Definition namegen.hpp:269
std::uint64_t seed() const
Retrieve the random seed used to generate this name.
Definition namegen.hpp:254
Name generator that produces culture-aware names and surnames.
Definition namegen.hpp:432
std::vector< name > get_surname_batch(const name_request &request, const core::batch_options &options)
Generate a batch of surname results from a seed drawn like get_surname() draws its own.
Definition namegen.hpp:627
ng & operator=(const ng &)=delete
Not copyable.
std::wstring female_form(const std::wstring &surname, culture c, bool married=false) const
The female form of a male surname, by the culture's surname_forms.tsv rules.
Definition namegen.hpp:1002
ng(const ng &)=delete
Not copyable.
name get_full_name(const name_request &request)
Generate a full name by the culture's convention.
Definition namegen.hpp:716
static std::string_view culture_name(culture c)
The name of a culture.
Definition namegen.hpp:492
name get_name(const name_request &request, std::uint64_t call_seed) const
Generate a deterministic first name using a specific seed.
Definition namegen.hpp:513
static std::wstring patronymic_of(patronymic_style style, const std::wstring &father, bool daughter)
The patronymic a father's given name gives a child.
Definition namegen.hpp:989
name compose_name(const name_parts &parts, culture c, std::uint64_t call_seed=0) const
A name made from words the caller already has, put in the culture's order and carrying the roles of i...
Definition namegen.hpp:885
name get_child_name(const name &father, const name &mother, const child_name_request &request)
Name a child of two people by the culture's convention.
Definition namegen.hpp:812
void for_each_full_name(const name_request &request, const core::batch_options &options, std::uint64_t batch_seed, Sink &&sink) const
Stream a batch of full names to a sink, in index order.
Definition namegen.hpp:770
name get_name(const name_request &request)
Generate a first name.
Definition namegen.hpp:502
std::vector< name > get_full_name_batch(const name_request &request, const core::batch_options &options, std::uint64_t batch_seed) const
Generate a batch of full names, deterministically: item i is get_full_name(request,...
Definition namegen.hpp:755
const std::vector< core::layer_info > & layers(culture c, gender g) const
The layers in effect for one name list.
Definition namegen.hpp:1198
bool has_resources() const
Check whether any name databases have been loaded.
Definition namegen.hpp:1024
void for_each_surname(const name_request &request, const core::batch_options &options, std::uint64_t batch_seed, Sink &&sink) const
Stream a batch of surname results to a sink without holding the whole batch.
Definition namegen.hpp:670
std::vector< name > get_name_batch(const name_request &request, const core::batch_options &options)
Generate a batch of name results from a seed drawn like get_name() draws its own.
Definition namegen.hpp:530
const core::layer_info & extend_from_string(std::string_view text, std::string source, core::layer_mode mode=core::layer_mode::override)
Add a name layer from text in the .names format.
Definition namegen.hpp:1181
std::vector< name > get_surname_batch(const name_request &request, const core::batch_options &options, std::uint64_t batch_seed) const
Generate a batch of surname results, deterministically.
Definition namegen.hpp:648
const std::vector< core::layer_info > & surname_form_layers() const
The layers in effect for surname_forms.tsv.
Definition namegen.hpp:1017
name get_surname(const name_request &request)
Generate a surname.
Definition namegen.hpp:600
ng()=default
Default constructor — creates an empty generator with no names.
void for_each_full_name(const name_request &request, const core::batch_options &options, Sink &&sink)
Stream a batch of full names with a batch seed drawn like get_full_name() draws its own.
Definition namegen.hpp:785
std::vector< name > get_full_name_batch(const name_request &request, const core::batch_options &options)
Generate a batch of full names from a seed drawn like get_full_name() draws its own.
Definition namegen.hpp:743
const core::layer_info & extend_surname_forms_from_string(std::string_view text, std::string source, core::layer_mode mode=core::layer_mode::override)
Add a layer of surname_forms.tsv from text.
Definition namegen.hpp:1161
const core::layer_info & extend_conventions_from_string(std::string_view text, std::string source, core::layer_mode mode=core::layer_mode::override)
Add a layer of conventions.tsv from text.
Definition namegen.hpp:1141
name get_married_name(const name &wife, const name &husband) const
The name a woman has after marrying, by the culture's convention.
Definition namegen.hpp:859
const std::vector< core::layer_info > & surname_layers(culture c, gender g) const
The layers in effect for the surnames of one gender.
Definition namegen.hpp:1210
bool load(dataset tier)
Load a dataset tier, replacing all names and layers loaded before.
Definition namegen.hpp:1058
static gender to_gender(std::wstring_view gender_string)
Translate a gender string to a gender enum.
Definition namegen.hpp:473
void load(const std::filesystem::path &resource_path)
Load name files from a directory, replacing all names and layers loaded before.
Definition namegen.hpp:1040
static ng & instance()
Access the global singleton instance.
Definition namegen.hpp:451
naming_convention convention(culture c) const
How a culture composes a full name.
Definition namegen.hpp:698
void for_each_surname(const name_request &request, const core::batch_options &options, Sink &&sink)
Stream a batch of surname results with a batch seed drawn like get_surname() draws its own.
Definition namegen.hpp:685
std::vector< name > get_name_batch(const name_request &request, const core::batch_options &options, std::uint64_t batch_seed) const
Generate a batch of name results, deterministically.
Definition namegen.hpp:551
const std::vector< core::layer_info > & convention_layers() const
The layers in effect for conventions.tsv.
Definition namegen.hpp:1010
void extend(const std::filesystem::path &path, core::layer_mode mode=core::layer_mode::override)
Add name layers from a .names file or a directory of them.
Definition namegen.hpp:1102
name get_parent_name(const name &child, gender parent_gender)
Name a parent of an existing person, consistently with the person's name; the inverse of get_child_na...
Definition namegen.hpp:915
name get_parent_name(const name &child, gender parent_gender, std::uint64_t call_seed) const
Name a parent of an existing person, deterministically.
Definition namegen.hpp:928
void for_each_name(const name_request &request, const core::batch_options &options, std::uint64_t batch_seed, Sink &&sink) const
Stream a batch of name results to a sink without holding the whole batch.
Definition namegen.hpp:573
void for_each_name(const name_request &request, const core::batch_options &options, Sink &&sink)
Stream a batch of name results with a batch seed drawn like get_name() draws its own.
Definition namegen.hpp:588
name get_surname(const name_request &request, std::uint64_t call_seed) const
Generate a deterministic surname using a specific seed.
Definition namegen.hpp:610
name get_child_name(const name &father, const name &mother, const child_name_request &request, std::uint64_t call_seed) const
Name a child of two people, deterministically.
Definition namegen.hpp:827
name get_full_name(const name_request &request, std::uint64_t call_seed) const
Generate a deterministic full name.
Definition namegen.hpp:728
ng(ng &&) noexcept=default
Move constructor.
static culture to_culture(std::wstring_view country_code)
Translate an ISO 3166 2-letter country code to a culture enum.
Definition namegen.hpp:460
static std::string_view culture_code(culture c)
The ISO 3166 2-letter country code of a culture.
Definition namegen.hpp:483
std::uint64_t data_hash() const
Hash of the loaded names, recorded in each result's signature().
Definition namegen.hpp:1221
patronymic_style
How a culture forms a patronymic from the father's given name.
Definition namegen.hpp:189
@ east_slavic
Ivan gives Ivanovich or Ivanovna.
surname_order
Which parents' surnames a child of a two-surname culture takes, and in what order.
Definition namegen.hpp:198
@ maternal_first
The mother's last surname, then the father's last (Portugal).
@ paternal_first
The father's first surname, then the mother's first (Spain).
name_order
The order a culture writes the given and the family name in.
Definition namegen.hpp:182
@ given_family
John Smith.
@ family_given
Kim Minjun.
name_role
The part of a full name a word is.
Definition namegen.hpp:219
@ family2
The second surname of a double surname.
culture
Culture representing a country or a broader group.
Definition namegen.hpp:48
gender
Simple gender enum to distinguish between male and female names.
Definition namegen.hpp:159
The per-call choices of ng::get_child_name().
Definition namegen.hpp:237
dasmig::gender gender
The child's gender; any draws one.
Definition namegen.hpp:238
The words of a name the caller already has; see ng::compose_name().
Definition namegen.hpp:228
dasmig::gender gender
m or f.
Definition namegen.hpp:229
std::wstring given
The given name.
Definition namegen.hpp:230
std::vector< std::wstring > family
One surname, or two; empty for none.
Definition namegen.hpp:232
std::wstring patronymic
The patronymic; empty for none.
Definition namegen.hpp:231
The per-call choices of a generation: gender and culture.
Definition namegen.hpp:175
dasmig::culture culture
Requested culture.
Definition namegen.hpp:177
dasmig::gender gender
Requested gender.
Definition namegen.hpp:176
How a culture composes a full name; see ng::convention().
Definition namegen.hpp:208
int surnames
1, or 2 for cultures with a double surname.
Definition namegen.hpp:212
double second_surname
Chance of the second surname when surnames is 2.
Definition namegen.hpp:213
patronymic_style patronymic
How the patronymic is formed.
Definition namegen.hpp:210
bool family_name
False when the patronymic replaces the family name.
Definition namegen.hpp:211
surname_order inheritance
Which parents' surnames a child takes.
Definition namegen.hpp:214
name_order order
Given or family name first.
Definition namegen.hpp:209