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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
//! Port of `lang_CKB.py` (Central Kurdish / Sorani, Latin transliteration).
//!
//! Registry check: `CONVERTER_CLASSES["ckb"]` is `lang_CKB.Num2Word_CKB()`
//! (`__init__.py:381`), which is the class ported here.
//!
//! Shape: **self-contained**. `Num2Word_CKB` subclasses `Num2Word_Base` but
//! defines no `high_numwords`/`mid_numwords`/`low_numwords`, so Python never
//! enters the `__init__` branch that builds `self.cards` / `set_numwords()` /
//! `self.MAXVAL`. Both `self.cards` and `self.MAXVAL` therefore **never exist**
//! on a CKB instance. `to_cardinal` is overridden outright and drives a
//! recursive `_int_to_word`, so `cards`/`maxval`/`merge` stay at their trait
//! defaults here and are never consulted. There is **no overflow check** and
//! no `OverflowError` path — see bug 1 below for what happens instead.
//!
//! Inherited from `Num2Word_Base`, but every one of them is overridden by CKB,
//! so nothing is picked up from the base class in the four modes in scope:
//! * `to_cardinal`, `to_ordinal`, `to_ordinal_num`, `to_year` — all defined
//! in `lang_CKB.py` itself.
//!
//! # The float/Decimal path
//!
//! CKB does **not** override `to_cardinal_float`, and it never reaches
//! `Num2Word_Base.to_cardinal_float` either: `num2words()` dispatches every
//! non-integer straight to `converter.to_cardinal(number)`, and CKB's override
//! swallows floats itself. So `base.float2tuple` — and with it the entire f64
//! `post = abs(value - pre) * 10**precision` / `< 0.01` heuristic that
//! `floatpath.rs` exists to reproduce — **is never executed for CKB**.
//!
//! CKB's first statement is `n = str(number).strip()`, and everything after it
//! is string surgery on that repr. The consequences run the opposite way to the
//! base class's:
//!
//! * **No f64 artefacts.** `repr` is shortest-round-trip, so `2.675` spells
//! `"2.675"` and `1.005` spells `"1.005"` — the exact cases where
//! `float2tuple` produces `674.9999999999998` and needs rescuing. Here the
//! noise never appears, so there is nothing to rescue and no `round()` to get
//! banker's-wrong. Corpus confirms both: `2.675` → `"du xał şeş hewt pênc"`.
//! * **No rounding, no padding, no `precision`.** The fraction is however many
//! digits the repr happened to carry, one word each. `Decimal("1.10")` keeps
//! its written trailing zero (`"yek xał yek sifir"`) where the float `1.1`
//! could not — the `Decimal`/`float` split is *visible* in the output, not
//! just in the last bits.
//! * **`precision=` is inert** — see [`LangCkb::to_cardinal_float`].
//! * **An exponential repr is a `ValueError`, not a number** — see bug 10.
//!
//! `Num2Word_CKB.to_cardinal` is byte-for-byte `Num2Word_CEB.to_cardinal` with
//! `"siro"` swapped for `"sifir"`, so [`LangCkb::cardinal_from_repr`] and
//! `lang_ceb.rs`'s `cardinal_from_repr` are the same port. The two crates'
//! copies of [`py_str_f64`] / [`py_str_decimal`] are deliberate duplicates: a
//! shared helper would have to live in `base.rs` or `floatpath.rs`, which this
//! phase may not touch. See `concerns`.
//!
//! `Num2Word_Base.to_cardinal` would have called `self.title(...)`; CKB's
//! override does **not**, so `is_title`/`exclude_title` are inert for the four
//! modes in scope. `setup()`'s `exclude_title = ["û", "xał", "negatîv"]` is
//! mirrored on the struct for fidelity but is never read: `is_title` stays
//! `false` (set in `Num2Word_Base.__init__`) and `title` is never reached.
//!
//! # Faithfully reproduced Python bugs
//!
//! This is a port, not a rewrite. The following look wrong but are exactly
//! what Python emits, and are confirmed by the frozen corpus:
//!
//! 1. **`_int_to_word` gives up at 10^9 and returns the decimal digits.** The
//! final line of the if-chain is a bare `return str(number)` — no billion
//! word exists in the table (`setup` stops at `million = "milyon"`). So
//! `to_cardinal(10**9)` == `"1000000000"`, and `to_ordinal(10**9)` ==
//! `"1000000000em"` — digits with a word suffix glued on. Corpus rows for
//! 10^9, 1234567890, 10^10, 10^11, 10^12, 10^15, 10^18 and 10^21 all
//! confirm this. It is unbounded: no exception is ever raised, however
//! large the input. Modelled in [`LangCkb::int_to_word`].
//! Negatives compose with it: `to_cardinal(-10**9)` == `"negatîv 1000000000"`.
//! 2. **`tens[1] == "de"` is dead.** 10..=19 are caught by the `number < 20`
//! branch and served from `teens`, so the `< 100` branch never divides down
//! to a tens index of 1. The entry is kept verbatim in [`TENS`] anyway.
//! 3. **`ones[0] == ""` is dead** on the integer path — `_int_to_word` handles
//! 0 before the `number < 10` branch. Python only reads `ones[0]` from the
//! float branch, where `self.ones[int(digit)] or "sifir"` relies on the
//! empty string being *falsy* to turn a fraction digit 0 into a word. That
//! is a different mechanism from `_int_to_word`'s explicit `if number == 0`;
//! both are live and both are needed. Corpus: `1.0` → `"yek xał sifir"`.
//! 4. **`to_ordinal` is pure concatenation**: `to_cardinal(n) + "em"`, with no
//! joint and no stem change. So the suffix lands on the *last* word only:
//! `to_ordinal(999)` == `"no sed û nod û noem"`, and `to_ordinal(-1)` ==
//! `"negatîv yekem"`. Unlike most languages there is no negative-ordinal
//! guard, so no `ValueError`/`TypeError` for negative ordinals.
//! 5. **`_int_to_word` would index `ones`/`teens` with a negative index** if it
//! were ever handed a negative number (Python's negative indexing wraps, so
//! `ones[-5]` would silently yield `"pênc"`). It is unreachable: the only
//! two callers, `to_cardinal` and `to_currency`, strip the sign / take
//! `abs()` first. [`LangCkb::int_to_word`] is only ever called with a
//! non-negative value here, mirroring that. The float path does not change
//! this: `cardinal_from_repr` peels the `"-"` off the *string* before any
//! `int()` runs, so `left` is always non-negative too.
//! 10. **A float whose repr goes exponential is a `ValueError`, not a number.**
//! Nothing filters the repr before it reaches `int()`, so every value
//! CPython spells with an `e` crashes — and *where* it crashes depends on
//! whether the mantissa has a fractional part, which changes the message:
//! * `1e16` → repr `"1e+16"` → no `"."` → `int("1e+16")` raises
//! `ValueError: invalid literal for int() with base 10: '1e+16'`.
//! * `1.5e16` → repr `"1.5e+16"` → splits to `left="1"`, `right="5e+16"`;
//! `"yek xał pênc"` is built successfully and then thrown away when the
//! loop hits `int('e')` → `ValueError: invalid literal for int() with
//! base 10: 'e'`. The offending token is the single *character*, not the
//! whole fragment.
//! * `1e-05` (i.e. any `abs(v) < 1e-4`) → `"1e-05"` → same as `1e16`.
//! * `inf` / `nan` → `int("inf")` / `int("nan")` → same shape.
//!
//! So CKB's float path is only total on `-4 < decpt <= 16`. Both messages
//! are reproduced verbatim; see [`py_int`] and [`py_int_digit`].
//!
//! # Error variants
//!
//! `N2WError::Value` (Python `ValueError`), and only from the float path —
//! bug 10's `int()` failures on an exponential/non-finite repr. Every *integer*
//! input in the four modes in scope still returns `Ok`: CKB has no overflow
//! ceiling (bug 1), no negative-ordinal guard (bug 4) and no dict lookups that
//! can miss, and `str` of a `BigInt` is never exponential. The 20 non-`ok`
//! corpus rows for `ckb` are all `cheque:*` (`NotImplementedError`) and
//! `fraction` (`TypeError`), both out of scope.
use crate;
use crate;
use crateFloatValue;
use crate;
use BigDecimal;
use BigInt;
use ;
use HashMap;
use FromStr;
/// `setup`: `self.negword`. Note the **trailing space** — CKB's `to_cardinal`
/// concatenates it directly (`self.negword + ...`) rather than joining with a
/// separator, so the space is what separates "negatîv" from the number.
const NEGWORD: &str = "negatîv ";
/// `setup`: `self.pointword`. Float path only; inert for the modes in scope.
const POINTWORD: &str = "xał";
/// `_int_to_word`'s zero word. Not in `ones` — `ones[0]` is `""` (bug 3).
const ZERO: &str = "sifir";
/// `setup`: `self.ones`. Index 0 is `""` and dead on the integer path (bug 3).
const ONES: = ;
/// `setup`: `self.teens`, indexed by `number - 10` for 10..=19.
const TEENS: = ;
/// `setup`: `self.tens`, indexed by `number // 10`. Index 0 is `""` (dead: the
/// `< 100` branch is only reached for `number >= 20`) and index 1 is `"de"`
/// (also dead — see bug 2).
const TENS: = ;
/// `setup`: `self.hundred`.
const HUNDRED: &str = "sed";
/// `setup`: `self.thousand`.
const THOUSAND: &str = "hezar";
/// `setup`: `self.million`. The largest scale word CKB defines — hence bug 1.
const MILLION: &str = "milyon";
/// The joint between every pair of groups: `" û "` ("and").
const JOINT: &str = " û ";
/// `to_ordinal` / `to_ordinal_num` suffix, glued on with no separator.
const ORDINAL_SUFFIX: &str = "em";
/// The ceiling of `_int_to_word`'s word-producing branches. At or above this,
/// Python falls through to `return str(number)` (bug 1).
const BILLION: u64 = 1_000_000_000;
/// `self.__class__.__name__`, for `to_cheque`'s NotImplementedError message.
const LANG_NAME: &str = "Num2Word_CKB";
/// The subunit divisor CKB's `to_currency` **hardcodes**.
///
/// `Num2Word_CKB.to_currency` reads exactly two fractional digits —
/// `int(parts[1][:2].ljust(2, "0"))` — and never consults
/// `CURRENCY_PRECISION`. So every code is 2-decimal on the `to_currency` path,
/// including the 3-decimal (KWD/BHD) and 0-decimal (JPY) ones. See bug 8.
///
/// This is *not* `currency_precision`, which stays at the trait default of 100
/// because `Num2Word_CKB` inherits `Num2Word_Base.CURRENCY_PRECISION == {}`
/// (verified live: it is still the unmutated base dict). The two happen to
/// agree at 100, but they are independent knobs — `to_cheque` reads the former,
/// `to_currency` this one.
const CENTS_PER_UNIT: i64 = 100;
/// The code whose forms `to_currency` falls back to for an unknown currency.
///
/// Python writes `self.CURRENCY_FORMS.get(currency, list(self.CURRENCY_FORMS.values())[0])`
/// — the *first inserted* entry, since dicts preserve insertion order. The
/// class body lists IQD first, so the fallback is IQD. Verified live:
/// `list(CURRENCY_FORMS.keys()) == ['IQD', 'IRR', 'USD', 'EUR']`. See bug 7.
const FALLBACK_CURRENCY: &str = "IQD";
/// The `< 10^9` body of `_int_to_word`, on `u64`.
///
/// The branch order mirrors Python's if-chain exactly. `divmod` on
/// non-negative operands is the same in both languages, so `/` and `%` are
/// direct equivalents here (no floor-division discrepancy to worry about —
/// the value is never negative).
/// Python's `int(s)` for a whole token, as `to_cardinal` calls it on `n` and on
/// `left`.
///
/// The `ValueError` message quotes the entire offending string, matching
/// CPython — that is why `1e+16` reports `'1e+16'` (bug 10).
///
/// `BigInt::from_str` is stricter than `int()` in three ways that no repr can
/// reach: `int()` also accepts surrounding whitespace, an underscore digit
/// separator (`int("1_0") == 10`), and any Unicode `Nd` codepoint. None of
/// those occur in a fragment of `str(float)` or `str(Decimal)`, and both agree
/// on a leading `+`/`-` and on rejecting `""` and `"e"`.
/// Python's `int(ch)` for a *single* character, as the fraction loop calls it.
///
/// The message quotes the one offending character, so `1.5e+16` reports `'e'`
/// rather than `'5e+16'` (bug 10). `char::to_digit(10)` is ASCII-only where
/// CPython's `int()` accepts `'٥'`; unreachable, since no repr emits a
/// non-ASCII digit.
/// The shortest round-trip decimal digits of `a` (finite, non-negative), plus
/// CPython's `decpt`: the value is `0.<digits> * 10^decpt`.
///
/// # Why `{:e}` alone is not enough
///
/// Rust's `{:e}` and CPython's `repr` are both "the shortest string that reads
/// back as the same double", and they agree on the digit *count* always and on
/// the digits themselves almost always. They part company on an **exact tie**,
/// where two equally-short decimals are equidistant from the true value and
/// both round-trip: CPython's `_Py_dg_dtoa` breaks the tie to **even**, Rust's
/// `flt2dec` shortest breaks it **away from zero**. The double whose exact
/// value is `670352580196876.25` sits precisely between `...876.2` and
/// `...876.3`, so `repr` says `.2` and `{:e}` says `.3`.
///
/// This is the same banker's-rounding trap `floatpath.rs` documents for
/// `round()`, relocated into the formatter — and it matters here for the same
/// reason: CKB's whole float path *is* the repr string, so a wrong last digit
/// is a wrong word.
///
/// # The fix
///
/// Rust's *fixed-precision* `{:.*e}` is correctly rounded half-to-even, so
/// re-emitting the same number of significant digits through it applies
/// CPython's tie rule. It is kept only if it still round-trips, so a
/// hypothetical asymmetric rounding interval (near a power of two, where the
/// nearer decimal can sit outside the interval) falls back to the shortest
/// digits rather than silently producing a string that reads back as a
/// different double.
/// CPython's `str(float)` / `repr(float)`, which is where CKB's float path
/// begins and ends.
///
/// `PyOS_double_to_string(v, 'r', 0, Py_DTSF_ADD_DOT_0)` in `pystrtod.c`:
/// take the shortest round-trip digits, then
///
/// * switch to exponent form when `decpt <= -4 || decpt > 16` — hence
/// `str(1e15) == "1000000000000000.0"` but `str(1e16) == "1e+16"`, and
/// `str(0.0001) == "0.0001"` but `str(1e-05) == "1e-05"`. (CPython moved this
/// threshold down from 1e17 so that `repr(2e16+8)` stops claiming
/// `20000000000000010.0` for a value that is really `...008.0`.) Everything
/// on the far side of that boundary is bug 10's `ValueError`.
/// * format that exponent `%+.02d` — signed, at least two digits, so `1e+16`
/// and `1e-05` but `5e-324`.
/// * otherwise print positionally and append `.0` if nothing follows the point
/// (`Py_DTSF_ADD_DOT_0`), which is the whole reason `1.0` is `"yek xał sifir"`
/// and not `"yek"`.
/// CPython's `Decimal.__str__` (the spec's `to-scientific-string`), ported from
/// `_pydecimal.Decimal.__str__`.
///
/// ```python
/// leftdigits = self._exp + len(self._int)
/// if self._exp <= 0 and leftdigits > -6:
/// dotplace = leftdigits # positional
/// else:
/// dotplace = 1 # scientific
/// ```
///
/// # Why this cannot just be `BigDecimal`'s `Display`
///
/// The two disagree in three places, each of which would change CKB's output or
/// its exception:
///
/// | value | `Decimal.__str__` | `BigDecimal` `Display` |
/// |---|---|---|
/// | `1E+2` | `1E+2` (CKB: `ValueError`) | `100` (CKB: "sed") |
/// | `0.0` | `0.0` (CKB: "sifir xał sifir") | `0` (CKB: "sifir") |
/// | `1E+16` | `1E+16` | `1e+16` — lowercase |
///
/// So the digits and exponent are read off `as_bigint_and_exponent()` and
/// reassembled by Python's rule instead. That pairing is exact:
/// `BigDecimal::from_str` keeps the written scale rather than normalising
/// (`"1.10"` stays coefficient 110 / scale 2, which is what makes the trailing
/// "sifir" appear), and `(coefficient, -scale)` is precisely Python's
/// `(_int, _exp)` — including for values Python itself cannot tell apart, since
/// `Decimal("1E-7")` and `Decimal("0.0000001")` *are* the same object and both
/// stringify "1E-7".
///
/// One known divergence: negative zero. See [`LangCkb::to_cardinal_float`].