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
//! Port of `lang_KZ.py` (Kazakh).
//!
//! Shape: **self-contained**. `Num2Word_KZ` subclasses `Num2Word_Base` but
//! defines no `high_numwords`/`mid_numwords`/`low_numwords`, so Python never
//! builds `self.cards` and never sets `MAXVAL`. `to_cardinal` is overridden
//! outright and drives `_int2word` over 3-digit chunks. Consequently
//! `cards`/`maxval`/`merge` stay at their trait defaults here, and there is
//! **no overflow check** — the only ceiling is the `THOUSANDS` table, which
//! raises `KeyError` rather than `OverflowError` (see below).
//!
//! `setup()` sets `negword = "минус"` and `pointword = "бүтін"`.
//!
//! Inherited from `Num2Word_Base` (unchanged by KZ, so the trait defaults do
//! the right thing):
//! * `to_ordinal_num(value) -> value` → default `Ok(value.to_string())`
//! (verified: corpus `ordinal_num` of `-1` is `"-1"`, of `0` is `"0"`).
//! * `to_year(value) -> self.to_cardinal(value)` → default delegates
//! through `&self`, picking up the `to_cardinal` override below. Kazakh
//! has no special year form: `to_year(1999)` == `to_cardinal(1999)` ==
//! "бір мың тоғыз жүз тоқсан тоғыз".
//!
//! The currency surface (`CURRENCY_FORMS`, `pluralize`, `_cents_verbose`) is
//! ported below. The `"." in n` branch of `to_cardinal` — which only fires for
//! float/Decimal input — is now ported as `to_cardinal_float` (see
//! "Float / Decimal cardinal path" below). For integer input `str(number)`
//! never contains `,` or `.`, so `to_cardinal` still reduces to
//! `self._int2word(int(n))`.
//!
//! No cross-call mutable state: KZ defines no `str_to_number` override and
//! stashes no flags between methods.
//!
//! # Float / Decimal cardinal path (`to_cardinal_float`)
//!
//! Python overrides **`to_cardinal`**, not `to_cardinal_float`, and handles
//! non-integers inline: `n = str(number).replace(",", ".")`, and on `"." in n`
//! it splits `left.right`, spells `int(left)` and — crucially — `int(right)` as
//! a *single whole number* (not digit by digit), prefixing one "нөл" per
//! leading zero of `right`, then joins `left бүтін <zeros> <int(right)>`. A
//! leading "минус" is added for any negative. It never reads `self.precision`,
//! so the `precision=` kwarg (issue #580 → `precision_override`) is **inert**
//! — confirmed live: `num2words(1.5,'kz',precision=5)` and `precision=0` both
//! give "бір бүтін бес". The Rust core splits int-cardinal (`to_cardinal`,
//! `&BigInt`) from float-cardinal (`to_cardinal_float`, `&FloatValue`), so
//! KZ's `"." in n` branch is ported into the `to_cardinal_float` override.
//!
//! `right` (Python's fractional digit string) is reconstructed from
//! `float2tuple`'s `post`, zero-padded to `precision`. That is exact for KZ:
//! `precision` is by construction the number of fractional digits in
//! `str(number)` (`abs(Decimal(str(f)).as_tuple().exponent)` for floats, the
//! Decimal scale otherwise), so `post` == `int(right)` and the padded string ==
//! `right`. Using `float2tuple` keeps the load-bearing f64 arithmetic and its
//! `< 0.01` rescue heuristic (e.g. `2.675` → `674.999…` → `675`) intact rather
//! than recomputing from a decimal string.
//!
//! This differs from `Num2Word_Base.to_cardinal_float` (the trait default) in
//! two ways that make the default wrong for KZ: (1) Base spells the fraction
//! digit by digit ("отыз төрт" vs Base "үш төрт" for `.34`); (2) Base prepends
//! the negword only when `pre == 0`, KZ always prepends it for negatives.
//!
//! ```text
//! to_cardinal(1.23) KZ: "бір бүтін жиырма үш" Base: "бір бүтін екі үш"
//! to_cardinal(0.25) KZ: "нөл бүтін жиырма бес" Base: "нөл бүтін екі бес"
//! to_cardinal(1.1) KZ: "бір бүтін бір" Base: "бір бүтін бір" (agree)
//! ```
//!
//! # Fractional cents still diverge (currency gap, deferred to the currency phase)
//!
//! `base.to_currency` renders fractional cents (a subunit that is not a whole
//! number, e.g. 65.3 cents) as `self.to_cardinal(float(right))` — a *virtual*
//! call, so Python lands in **KZ's** float branch (whole-number spelling),
//! which the `to_cardinal_float` override above now reproduces. The trait's
//! **`cardinal_from_decimal`** default, however, still routes to `floatpath`
//! (Base's digit-by-digit spelling), so it disagrees with KZ whenever the
//! fractional cents carry two or more significant digits. It is **left at the
//! default here**: this is the currency surface (a separate, later fixup phase),
//! and no corpus row reaches it — every KZ `currency:USD` case has at most two
//! decimals, so `right` is a whole number of cents and the branch never fires.
//! Flagged rather than patched — see the report's `concerns`.
//!
//! # Faithfully reproduced Python bugs
//!
//! This is a port, not a rewrite. `to_ordinal` picks its suffix by testing the
//! cardinal's final character against three hand-written character classes.
//! Those classes are **incomplete**, and the resulting wrong forms are exactly
//! what Python emits — every one below is confirmed against the frozen corpus:
//!
//! 1. `қ` (U+049B) is **missing** from the consonant class, and no vowel class
//! matches it either, so "қырық" (40) falls through to the `else` arm and
//! takes the front-vowel suffix: `to_ordinal(40)` == "қырықінші".
//! Idiomatic Kazakh is "қырқыншы".
//! 2. The vowel arms append `ншы`/`нші` with no linking consonant, so
//! `to_ordinal(20)` == "жиырманшы" (idiomatic: "жиырмасыншы").
//! 3. The back/front decision for consonant-final words inspects only the last
//! **two** characters, so "миллиард" (last two = "рд", no back vowel) is
//! misfiled as front: `to_ordinal(10**9)` == "бір миллиардінші"
//! (idiomatic: "бір миллиардыншы"). "триллион" and friends escape this only
//! because their last two characters are "он".
//! 4. `у` (U+0443) appears in no class at all, so "елу" (50) also reaches the
//! `else` arm. Here the fallback happens to be right: "елуінші".
//! 5. There is no "one thousand" elision: `to_cardinal(1000)` == "бір мың",
//! not "мың". Kept verbatim.
//!
//! # Error variants
//!
//! `THOUSANDS` has keys 1..=10 (up to "нониллион" == 1000^10 == 10^30), so the
//! largest representable value is 10^33 - 1 (11 chunks, top chunk index 10).
//! At 10^33 the top chunk index becomes 11 and Python raises `KeyError: 11` —
//! a crash, not a deliberate raise, but the exception *type* is observable, so
//! parity means reproducing it rather than tidying it into an `OverflowError`.
//! Verified against the interpreter: `to_cardinal(10**33)` → `KeyError: 11`.
//! The corpus tops out at 10^21 ("бір секстиллион"), so this bound is
//! reproduced from the source and a live probe, not from corpus coverage.
//!
//! Unlike `lang_PL`, negatives are safe in every mode: `_int2word` strips the
//! sign and recurses on `abs(n)` *before* `splitbyx`/`get_digits` ever see the
//! string, so no `'-'` survives into `int()`.
use crate;
use crateCurrencyForms;
use crate;
use crateParsedNumber;
use BigInt;
use ;
use HashMap;
const ZERO: &str = "нөл";
const NEGWORD: &str = "минус";
const TEN: &str = "он";
const HUNDRED: &str = "жүз";
/// `ONES`, keys 1..=9. Index 0 is absent in Python (guarded by `n1 > 0` /
/// `n3 > 1`), so the empty slot here is never read.
const ONES: = ;
/// `TWENTIES`, keys 2..=9. Indices 0 and 1 are absent in Python; `n2 == 1` is
/// handled separately by `TEN`, and `n2 == 0` appends nothing.
const TWENTIES: = ;
/// `THOUSANDS`, keys 1..=10. Index 0 is absent in Python (guarded by `i > 0`).
/// Index 11 and beyond do not exist — that is the `KeyError` ceiling.
const THOUSANDS: = ;
/// Vowels taking the bare `ншы` suffix: а о ұ ы е э.
const BACK_VOWELS: &str = "аоұыеэ";
/// Vowels taking the bare `нші` suffix: ә і ү ө.
const FRONT_VOWELS: &str = "әіүө";
/// The consonant class. Transcribed verbatim from Python — note that `қ`
/// (U+049B) and `у` (U+0443) are **absent**; see module bugs 1 and 4.
const CONSONANTS: &str = "бвгғджзйклмнңпрстфхһцчшщ";
/// Back vowels probed against the last two characters to choose `ыншы` over
/// `інші` after a consonant: а о ұ ы.
const LAST2_BACK: &str = "аоұы";
/// The suffix-selection tail of `Num2Word_KZ.to_ordinal`, shared by the
/// integer path and the float/Decimal entry (Python has one method; its
/// `cardinal = self.to_cardinal(number)` call is virtual over the input type,
/// so the same character inspection runs on "бес" and on "бес бүтін нөл нөл"
/// alike).
///
/// Python indexes `cardinal[-1]` unguarded. `to_cardinal` of a non-zero value
/// always yields at least one word, so the empty case is unreachable; an
/// empty string would be an IndexError in Python, so mirror that rather than
/// inventing a fallback.
/// `int(n)`'s ValueError for the no-`"."` branch of `to_cardinal`, reached
/// when `str(number)` came out in exponent form (`1e+16`, `1E+2`), or as
/// `inf`/`nan`. The message shape matches CPython's; only the exception type
/// is corpus-checked.
/// `str(number)` for a float that carries no visible point: exponent form for
/// finite values (`1e+16`), `inf`/`nan` otherwise. Only used to build the
/// `int()` ValueError message; the corpus checks exception *types*, so the
/// digits just need to be recognisably Python-shaped, not a full repr port.
/// Port of `utils.splitbyx(n, x)` with `x == 3` and `format_int=True`.
///
/// `n` is the decimal string of a **non-negative** integer here (`_int2word`
/// has already stripped any sign), so every chunk is 1..=3 digits and lies in
/// `0..=999`. That bound is what licenses `u32` rather than `BigInt`: the
/// chunk width is fixed by the slicing, not by the magnitude of the input.
/// The number of chunks is unbounded, but it is a length, so `usize` is fine.
/// Port of `utils.get_digits(n)`:
/// `[int(x) for x in reversed(list(("%03d" % n)[-3:]))]` → `[n1, n2, n3]`
/// (units, tens, hundreds).
///
/// Callers only ever pass a `splitbyx` chunk (`0..=999`), for which `"%03d"`
/// yields exactly three digits and the `[-3:]` slice is a no-op. The negative
/// hazard that breaks `lang_PL.to_ordinal` cannot arise here.
/// `Num2Word_KZ.CURRENCY_FORMS`, verbatim — two codes, and that is the whole
/// table.
///
/// KZ declares its own dict in the class body and subclasses `Num2Word_Base`
/// directly, so it never sees the `lang_EUR` table that `Num2Word_EN.__init__`
/// mutates in place, and none of EN's ~24 added codes leak in. Confirmed
/// against the live interpreter *after* import (i.e. after every converter has
/// been constructed and any in-place mutation has happened):
/// `{"KZT": ("теңге", "тиын"), "USD": ("доллар", "цент")}`. That is precisely
/// why the corpus expects `NotImplementedError` for EUR, GBP, JPY, KWD, BHD,
/// INR, CNY and CHF — 96 of KZ's 108 currency rows.
///
/// # The one-element arity is the port, not a shortcut
///
/// KZ's entries are **flat `(str, str)` pairs**, not the `(unit_forms,
/// subunit_forms)` pairs-of-tuples EN uses. `base.py` unpacks them as
/// `cr1, cr2 = ("доллар", "цент")`, so `cr1` is the *string* "доллар" and `cr2`
/// the *string* "цент" — there is no plural form to index. All three readers of
/// that shape are guarded to treat a non-tuple as an opaque whole:
///
/// * `pluralize(n, cr1)` — KZ's returns `form` unchanged (see below).
/// * `cr2[1] if isinstance(cr2, tuple) and len(cr2) > 1 else cr2` — a str, so
/// the whole string.
/// * `to_cheque`: `unit = cr1[-1] if isinstance(cr1, tuple) else cr1` — a str,
/// so the whole string. Without that `isinstance` guard, `cr1[-1]` on a str
/// would yield the last *character*, "р".
///
/// Modelling each side as a **one-element** `Vec` makes all three fall out of
/// the shared code correctly: `unit.last()` and `subunit.get(1).or(first())`
/// both return the single string. Adding a second form here would be a
/// plausible-looking "fix" — Kazakh does have "доллардар" — and would silently
/// change `to_cheque` and the fractional-cents branch to pick it up. Don't.