1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
//! Port of `lang_ZU.py` (Zulu / isiZulu).
//!
//! Registry check: `CONVERTER_CLASSES["zu"]` is `lang_ZU.Num2Word_ZU`
//! (`__init__.py:401`), so this is the class the key actually resolves to.
//!
//! Shape: **self-contained**. `Num2Word_ZU` subclasses `Num2Word_Base` but
//! defines no `high_numwords`/`mid_numwords`/`low_numwords`, so Python's
//! `Num2Word_Base.__init__` never builds `self.cards` and **never sets
//! `MAXVAL`**. Every in-scope entry point is overridden, so the engine
//! (`splitnum`/`clean`/`merge`) is unreachable and `cards`/`maxval`/`merge`
//! stay at their trait defaults. There is no overflow check at all — see the
//! `str(number)` fallthrough below.
//!
//! Nothing is inherited from `Num2Word_Base` in the integer scope: ZU overrides
//! `to_cardinal`, `to_ordinal`, `to_ordinal_num` and `to_year` outright.
//! (`to_year(self, val, longval=True)` ignores `longval` entirely and just
//! calls `to_cardinal`, which is why the trait's single-argument `to_year`
//! is a faithful signature here.)
//!
//! The currency surface is split: ZU overrides `to_currency` and `pluralize`,
//! but inherits `to_cheque`, `_money_verbose`, `_cents_verbose` and
//! `_cents_terse` from `Num2Word_Base` untouched — verified against the live
//! interpreter (`to_cheque.__func__.__qualname__ == "Num2Word_Base.to_cheque"`),
//! so those stay at their trait defaults here. `CURRENCY_ADJECTIVES` and
//! `CURRENCY_PRECISION` are both inherited *empty*, so every code resolves to
//! the default divisor 100 and `adjective=` can never fire; neither hook is
//! overridden.
//!
//! `CURRENCY_FORMS` is ZU's **own** class attribute, not `Num2Word_EUR`'s, so
//! the `lang_EUR.py` mutation trap (EN's `__init__` rewriting the shared class
//! dict in place) does not apply — `CONVERTER_CLASSES["zu"].CURRENCY_FORMS`
//! reads back exactly the three entries in the source literal, in source order.
//!
//! No cross-call mutable state: no method sets an instance flag that another
//! reads. `setup()` assigns only constant tables, and `self.precision` is
//! touched solely by the base class's float paths, which ZU never reaches:
//! its `to_cardinal` handles floats and Decimals inline as *string*
//! operations on `str(number)`, so `float2tuple`/`to_cardinal_float` from
//! `base.py` never run for this language. Consequently the `precision=`
//! kwarg (issue #580) is a **no-op** for ZU — the dispatcher sets
//! `converter.precision` (the attribute exists, `Num2Word_Base.__init__`
//! sets it to 2) but nothing on ZU's path ever reads it back — so the Rust
//! `to_cardinal_float` override ignores `precision_override`, verified live:
//! `num2words(0.5, lang="zu", precision=3)` == `"iqanda ichashazi kuhlanu"`.
//!
//! # Faithfully reproduced Python behaviour
//!
//! These all look wrong and are all exactly what Python emits. Verified
//! against the frozen corpus (`bench/corpus.jsonl`, lang "zu"):
//!
//! 1. **`_int_to_word` gives up at 10^9 and returns the raw decimal string.**
//! The final `return str(number)` has no guard: `to_cardinal(10**9)` ==
//! `"1000000000"`, not words, and no `OverflowError` is raised. Corpus
//! confirms this all the way to 10^21 (`"1000000000000000000000"`), so the
//! value must stay a `BigInt` — it is never bounded and never parsed.
//! Consequently `to_ordinal(10**9)` == `"we-1000000000"` and
//! `to_cardinal(-10**9)` == `"ngaphansi kwe 1000000000"`.
//! 2. **`negword` is `"ngaphansi kwe "` with a trailing space and is
//! concatenated raw**, not `"%s " % negword.strip()` the way
//! `Num2Word_Base.to_cardinal` does it. The spacing works out identically,
//! but the trailing `.strip()` in ZU's `to_cardinal` is what would absorb a
//! doubled space — it is a no-op for every reachable integer input.
//! 3. **`to_ordinal` never calls `verify_ordinal`**, so negatives and zero
//! sail through instead of raising `TypeError`: `to_ordinal(0)` ==
//! `"we-iqanda"` and `to_ordinal(-1)` == `"we-ngaphansi kwe kunye"` —
//! an ordinal prefix glued onto a negation. Corpus agrees.
//! 4. **`to_ordinal_num` interpolates the sign**: `"we-" + str(-1)` produces
//! the double hyphen `"we--1"`. Corpus agrees.
//! 5. **The `na` joiner is uniform and unelided.** Zulu orthography would
//! normally contract "na + i" (na + ikhulu → nekhulu), but the module just
//! concatenates `" na "`, yielding `"ikhulu na ishumi na kunye"` for 111
//! and `"inkulungwane na ikhulu"` for 1100. Preserved verbatim.
//! 6. **Scale words carry no multiplier when the quotient is 1** (`if h > 1`,
//! `if t > 1`), so 100 == `"ikhulu"` and 1000 == `"inkulungwane"` with no
//! leading "kunye" — but 2000 == `"kubili inkulungwane"`.
//! 7. **An unknown currency code does not raise — it silently borrows ZAR.**
//! `to_currency` looks the code up with
//! `.get(currency, list(self.CURRENCY_FORMS.values())[0])`, and ZAR is the
//! first key inserted, so `to_currency(1, "JPY")` == `"kunye randi"`: Zulu
//! rand for a yen amount. `to_cheque` is *not* ZU's, and does the strict
//! `self.CURRENCY_FORMS[currency]`, so `to_cheque(1234.56, "JPY")` raises
//! NotImplementedError on the same input. Both halves are corpus-pinned;
//! see [`FALLBACK_CODE`].
//! 8. **`_int_to_word`'s 10^9 digit-string fallthrough leaks into money.**
//! `to_currency(10**9, "ZAR")` == `"1000000000 randi"`, and
//! `to_currency(1000000000.5, "ZAR")` ==
//! `"1000000000 randi amashumi amahlanu isenti"` — bare digits next to a
//! spelled-out cents clause, because `to_currency` calls `_int_to_word`
//! directly rather than going through `to_cardinal`.
//! 9. **The float path is `str(number)` surgery, not arithmetic.** Digits
//! after the point are read one character at a time off the repr, so
//! `base.float2tuple`'s binary-rounding artefacts never arise: `2.675` →
//! `"2.675"` → `"... isithupha isikhombisa kuhlanu"` (6-7-5, no rescue
//! heuristic needed), Decimal trailing zeros survive (`Decimal("1.10")` →
//! `"kunye ichashazi kunye iqanda"`), and the 10^9 digit fallthrough
//! leaks into the integer part (`1234567890.5` →
//! `"1234567890 ichashazi kuhlanu"`). All corpus-pinned.
//! 10. **Exponent notation crashes it.** `str(float)` flips to scientific
//! below 1e-4 (`repr(1e-05)` == `"1e-05"`) and `str(Decimal)` below an
//! adjusted exponent of -6 (`str(Decimal("1E-7"))` == `"1E-7"`), and the
//! `int()` calls then choke: no-dot forms fail on the whole literal
//! (`int("1e-05")` → `ValueError: invalid literal for int() with base 10:
//! '1e-05'`), dotted forms fail on the first non-digit fraction char
//! (`1.5e-05` → right part `"5e-05"` → `int("e")` → `... 'e'`, and
//! `Decimal("1.05E-7")` → `... 'E'`). All four shapes verified live;
//! reproducing them requires reconstructing Python's exact float-repr /
//! Decimal-str spellings, which [`py_float_repr`]/[`py_decimal_str`] do.
//! 11. **`precision=` is dead** — see the header note; `_precision_override`
//! is deliberately unused in `to_cardinal_float`.
//!
//! # A note on the unreachable negative-index hazard
//!
//! `_int_to_word` does `self.ones[number]` for `number < 10` without a lower
//! bound. Reached with a negative it would silently wrap around Python's
//! negative list indexing (`ones[-1]` == `"isishiyagalolunye"`) rather than
//! raise. It is unreachable from the four in-scope entry points because
//! `to_cardinal` peels the sign off first, so this port takes `&BigInt`
//! non-negative in [`LangZu::int_to_word`] and does not model the wraparound.
use crate;
use crate;
use crateFloatValue;
use crate;
use BigDecimal;
use BigInt;
use Integer;
use ;
use HashMap;
/// `self.ones`. Index 0 is `""`; it is never reached by the integer modes
/// because `_int_to_word` returns "iqanda" for zero before the `< 10`
/// branch. (The float path *does* use `ones[0]`, hence the `or "iqanda"`
/// fallback in [`LangZu::str_cardinal`].)
const ONES: = ;
/// `self.tens`. Index 0 is `""` and unreachable (`number < 100` implies
/// `t >= 1` there, since `number < 10` was already handled).
const TENS: = ;
const ZERO_WORD: &str = "iqanda";
const HUNDRED: &str = "ikhulu";
const THOUSAND: &str = "inkulungwane";
const MILLION: &str = "isigidi";
const NEGWORD: &str = "ngaphansi kwe ";
const POINTWORD: &str = "ichashazi";
const JOINER: &str = " na ";
const ORDINAL_ONE: &str = "okokuqala";
const ORDINAL_PREFIX: &str = "we-";
/// The code `to_currency` falls back to for anything not in `CURRENCY_FORMS`.
///
/// Python writes the fallback positionally, not by name:
///
/// ```text
/// self.CURRENCY_FORMS.get(currency, list(self.CURRENCY_FORMS.values())[0])
/// ```
///
/// `list(dict.values())[0]` is the **first-inserted** entry under Python 3.7+
/// insertion-ordered dicts, and ZU's class body inserts ZAR, then USD, then
/// EUR. Pinning the name here rather than relying on `HashMap` iteration order
/// is the whole point: `HashMap` has no order to borrow, so a positional
/// transcription would be nondeterministic. Live-checked —
/// `list(CURRENCY_FORMS.keys()) == ["ZAR", "USD", "EUR"]`.
///
/// **Not the same thing as `default_currency()`**, even though both are "ZAR"
/// here. `default_currency()` is the signature default — what `currency`
/// becomes when the caller omits the kwarg (`to_currency(val,
/// currency="ZAR")`). `FALLBACK_CODE` is what a code the caller *did* pass but
/// that is missing from the table resolves to. They are independent: reordering
/// the class-body dict would move this one and leave the signature alone. Do
/// not collapse them.
const FALLBACK_CODE: &str = "ZAR";
/// Extract a 0..=9 `BigInt` as a `usize` index.
///
/// Every call site has already bounded the value below 10 (or is a `div_rem`
/// quotient/remainder that is), so the conversion cannot fail. Uses the
/// decimal string rather than `ToPrimitive` to avoid widening the import set.
/// Python's `int(s)` for the strings this module can produce.
///
/// The reachable inputs are pure ASCII digit runs (success) or repr/str
/// spellings carrying `e`/`E`/`+` exponent syntax (ValueError, quoting the
/// whole literal — `int("1e-05")` → `invalid literal for int() with base 10:
/// '1e-05'`). Signs never reach here: `to_cardinal` peels a leading `-`
/// before any `int()` call, and repr never emits an interior `+` outside the
/// exponent forms that fail anyway. Python's wider `int()` grammar
/// (whitespace, underscores, non-ASCII digits) is unreachable from
/// `str(float)`/`str(Decimal)` output, so it is not modelled.
/// Python's `repr(float)` (== `str(float)`) for a finite f64.
///
/// ZU's `to_cardinal` works on `str(number)`, so the exact spelling — where
/// the notation flips to scientific, the `.0` on whole floats, the two-digit
/// zero-padded exponent — is load-bearing. Rust's `{}` shares the
/// shortest-round-trip digits contract with CPython's repr but never uses
/// scientific notation, drops the `.0`, **and resolves exact-tie shortest
/// candidates differently**, so the string is rebuilt here:
///
/// * CPython (`format_float_short`, mode `'r'`) goes scientific when the
/// decimal-point position `decpt` is `<= -4` or `> 16`: `repr(0.0001)` ==
/// `'0.0001'` but `repr(0.00001)` == `'1e-05'`; `repr(1e16)` == `'1e+16'`
/// but `repr(9999999999999998.0)` keeps all 16 digits. `decpt` comes from
/// `{:e}`'s exponent (the shortest-length contract is shared, so the
/// digit *count* — and hence the regime — always agrees).
/// * **Positional regime — the tie trap.** When a float sits exactly
/// halfway between the two shortest candidates (coarse ulp, e.g.
/// `980819185788849.25` between `…849.2` and `…849.3`, both of which
/// round-trip), CPython's dtoa rounds half-to-EVEN (`…849.2`) while
/// Rust's `{}`/`{:e}` shortest digits land on `…849.3`. Randomized
/// cross-validation against the live interpreter caught four of these in
/// 1 500 samples, so this is not theoretical. The fix: format with
/// `{:.prec$}`, whose fixed mode rounds the *exact* binary expansion
/// half-to-even (verified: `{:.1}` of `0.25` → `"0.2"`, of
/// `980819185788849.25` → `"…849.2"`) — exactly repr's rounding at
/// repr's length. `prec` is the `FloatValue` precision field, computed on
/// the Python side as `abs(Decimal(str(value)).as_tuple().exponent)`,
/// i.e. repr's own fraction-digit count; `max(prec, 1)` restores the
/// mandatory `.0` of whole floats (`str(1.0)` == `"1.0"` — the corpus
/// `1.0` → `"kunye ichashazi iqanda"` row) should a whole value ever
/// arrive with precision 0. `{:.prec$}` also keeps `-0.0`'s sign.
/// * Scientific regime: `d[.ddd]e±XX`, exponent `%+03d`-shaped — sign
/// always present, at least two digits (`1e-05`, `1e+16`, `5e-324`).
/// Ties cannot arise here: an exact decimal midpoint at the last shortest
/// digit needs an ulp on the order of that digit's place, which only
/// coarse large-magnitude floats have — sub-1e-4 floats have ulps many
/// orders finer than their shortest digit grid. (For `decpt > 16` the
/// value is whole, which the dispatcher never routes here at all.)
/// Python's `str(Decimal)`, reconstructed from the parsed `BigDecimal`.
///
/// The binding sends `str(number)` and `BigDecimal::from_str` keeps the
/// coefficient and scale exactly as written (trailing zeros and `E±n`
/// exponents included), so CPython's `Decimal.__str__` algorithm — sign,
/// coefficient digits, exponent — round-trips the original spelling:
/// `"1.10"` stays `"1.10"`, `"0.0000001"` (arriving as `"1E-7"`) renders
/// back to `"1E-7"`, `"1.05E-7"` to `"1.05E-7"`. Positional iff
/// `_exp <= 0 and leftdigits > -6`; otherwise one digit left of the point
/// and an `E%+d` suffix (no zero padding, unlike float repr — verified live:
/// the ValueError literal for `Decimal("0.0000001")` is `'1E-7'`).
///
/// **One unreproducible spelling: negative zero.** `str(Decimal("-0.0"))`
/// keeps the sign, so Python emits the negword (`"ngaphansi kwe iqanda
/// ichashazi iqanda"`), but `BigInt` cannot carry a sign on zero and the
/// discriminator is destroyed by the `BigDecimal` parse one layer above this
/// file — same class of hole as the `e-` currency case below. This port
/// renders `Decimal("-0.0")` unsigned. The float `-0.0` is unaffected: f64
/// keeps its sign bit and `{:.prec$}` prints it. No corpus row exercises a
/// negative-zero Decimal.
/// Python's inline currency split, which is a **string** operation on
/// `str(abs(val))` rather than an arithmetic one:
///
/// ```text
/// parts = str(val).split(".")
/// left = int(parts[0]) if parts[0] else 0
/// right = int(parts[1][:2].ljust(2, "0")) if len(parts) > 1 and parts[1] else 0
/// ```
///
/// `to_currency` has already taken `abs` by this point; it is re-applied here
/// so the stringification and the split stay in one place.
///
/// Four consequences, all corpus-pinned:
///
/// * `right` comes from *right-padding the first two fraction digits*, not
/// from multiplying: `0.5` → `"5"` → `"50"` → 50 amasenti, while `0.05` →
/// `"05"` → 5. Anything past the second decimal is truncated with no
/// rounding at all, so `12.349` → 34 (not 35) and `0.005` → 0 (not 1).
/// * A fraction of `"0"` (i.e. `1.0`) yields `right == 0`, which `to_currency`
/// treats as falsy and drops the cents clause entirely: `1.0` → `"kunye
/// iyuro"`, not `"...iqanda isenti"`. This is the one point where ZU's float
/// path coincides with base's int-only path, and it is reached by ZU's own
/// route rather than by base's `has_decimal` guard — which is why
/// `CurrencyValue::Decimal`'s `has_decimal` flag is unused here.
/// * `Decimal("5")` (scale 0, no `"."` in `str`) and `Decimal("5.00")` (scale
/// 2, `right == 0`) both land on `"kuhlanu idola"` — by the two different
/// routes above, so the scale carries everything `has_decimal` would.
/// * A `CurrencyValue::Int` stringifies without a `"."`, so `parts` has length
/// 1 and `right` stays 0.
///
/// # The exponent-notation hole
///
/// `str(float)` flips to exponent notation at `|v| >= 1e16` and
/// `0 < |v| < 1e-4`, and `int()` then chokes on the literal:
/// `to_currency(1e16)` raises `ValueError: invalid literal for int() with base
/// 10: '1e+16'`. A negative `BigDecimal` scale is exactly the "the source
/// string used `e+` notation" signal — a plain digit string parses to scale 0,
/// never below — so that arm is reproduced faithfully.
///
/// The `e-` side is **not** reproducible from here, and is flagged in the port
/// report: Python raises `ValueError` for `1e-05` but returns `"iqanda idola"`
/// for `Decimal("0.00001")`. The two are distinguishable *in principle* — the
/// shim sends `str(value)`, and those strings differ (`"1e-05"` vs
/// `"0.00001"`) — but `BigDecimal::from_str` normalises both to digits 1 /
/// scale 5, and `CurrencyValue::Decimal` retains only the parsed value, not the
/// literal it came from. So the discriminator is destroyed by the parse, one
/// layer above this file. Fixing it means giving `CurrencyValue` the original
/// spelling (a `currency.rs` change affecting every language that transcribes
/// this same `str(val).split(".")` idiom — 63 of the Python modules do), which
/// is out of scope for a single-language port. This port takes the `Decimal`
/// reading for both. Corpus has no `e-` row, so nothing regresses today.