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
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
//! Circle Display and Debug formatting implementations.
//!
//! This module implements `Display` and `Debug` traits for `Circle<F, E>` types,
//! providing flexible complex number formatting in any base (2-36) with any number of digits.
//!
//! # Key Design Principle
//!
//! **All digit extraction uses Spirix arithmetic directly** - just like the Scalar formatter,
//! the Circle formatter does NOT convert numbers to u8 or use bitmasks. Instead, it:
//! 1. Formats each component (real and imaginary) using the same Spirix arithmetic as Scalar
//! 2. Uses `floor()` to separate integer and fractional parts
//! 3. Uses division and multiplication by the base to extract individual digits
//! 4. Uses `to_u8()` only for converting already-extracted single digits to characters
//!
//! # Circle Format
//!
//! Circle values are displayed as `⦇real,imaginary⦈` where both real and imaginary
//! components are formatted using the same algorithm as Scalar formatting.
//!
//! # Examples
//!
//! ```rust
//! use spirix::CircleF5E3;
//!
//! let z = CircleF5E3::new(3, 4); // 3 + 4i
//!
//! // Default formatting (base-10)
//! println!("{}", z); // ⦇+3,+4⦈
//!
//! // Hexadecimal (base-16)
//! println!("{:.16}", z); // ⦇+3,+4⦈
//!
//! // Binary (base-2) with 16 digits
//! println!("{:16.2}", z); // ⦇+11,+100⦈
//!
//! // Debug output shows internal bit pattern for both components
//! println!("{:?}", z);
//! ```
use crate::core::integer::FullInt;
use crate::core::undefined::*;
use crate::implementations::formatting::colours::{ColourScheme, COLOURS};
use crate::*;
use i256::I256;
use num_traits::{AsPrimitive, WrappingAdd, WrappingMul, WrappingNeg, WrappingSub};
use alloc::borrow::ToOwned;
use alloc::string::String;
use alloc::vec::Vec;
use ::core::fmt;
use ::core::ops::*;
impl<
F: Integer
+ FractionConstants
+ FullInt
+ Shl<isize, Output = F>
+ Shr<isize, Output = F>
+ Shl<F, Output = F>
+ Shr<F, Output = F>
+ Shl<E, Output = F>
+ Shr<E, Output = F>
+ WrappingNeg
+ WrappingAdd
+ WrappingMul
+ WrappingSub,
E: Integer
+ ExponentConstants
+ FullInt
+ Shl<isize, Output = E>
+ Shr<isize, Output = E>
+ Shl<E, Output = E>
+ Shr<E, Output = E>
+ Shl<F, Output = E>
+ Shr<F, Output = E>
+ WrappingNeg
+ WrappingAdd
+ WrappingMul
+ WrappingSub,
> fmt::Display for Circle<F, E>
where
Circle<F, E>: CircleConstants,
Scalar<F, E>: ScalarConstants,
u8: AsPrimitive<F>,
u16: AsPrimitive<F>,
u32: AsPrimitive<F>,
u64: AsPrimitive<F>,
u128: AsPrimitive<F>,
usize: AsPrimitive<F>,
i8: AsPrimitive<F>,
i16: AsPrimitive<F>,
i32: AsPrimitive<F>,
i64: AsPrimitive<F>,
i128: AsPrimitive<F>,
isize: AsPrimitive<F>,
I256: From<F>,
u8: AsPrimitive<E>,
u16: AsPrimitive<E>,
u32: AsPrimitive<E>,
u64: AsPrimitive<E>,
u128: AsPrimitive<E>,
usize: AsPrimitive<E>,
i8: AsPrimitive<E>,
i16: AsPrimitive<E>,
i32: AsPrimitive<E>,
i64: AsPrimitive<E>,
i128: AsPrimitive<E>,
isize: AsPrimitive<E>,
I256: From<E>,
Scalar<i128, i128>: From<Scalar<F, E>>,
{
/// Formats a Circle for display using precision and width specifiers.
///
/// # Format Parameters
///
/// - **Precision** (`.N`): Specifies the base (2-36). Default is 10.
/// - **Width** (`:N`): Specifies how many digits to display per component. Default is
/// calculated from the fraction bits as `log_base(2^fraction_bits)`.
///
/// # Examples
///
/// ```rust
/// use spirix::CircleF5E3;
/// let z = CircleF5E3::new(15, 31);
/// assert_eq!(format!("{:.16}", z), "⦇+F,+1F⦈"); // Hex
/// assert_eq!(format!("{:.2}", z), "⦇+1111,+11111⦈"); // Binary
/// assert_eq!(format!("{:3.10}", z), "⦇+15,+31⦈"); // Base-10, max 3 digits
/// ```
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Extract base from precision specifier (default: base-10)
let mut base: u8 = 10;
if let Some(prec) = f.precision() {
base = prec as u8;
if base < 2 || base > 36 {
return write!(f, "Error: Only bases 2-36 are supported!");
}
}
// Calculate default digit count based on fraction bit precision
// For very large fraction types, use a smaller type to avoid overflow
let mut digits = if F::FRACTION_BITS > 100 && E::EXPONENT_BITS < 12 {
crate::ScalarF7E4::TWO
.pow(F::FRACTION_BITS)
.log(base)
.floor()
.to_isize()
} else {
Scalar::<F, E>::TWO
.pow(F::FRACTION_BITS)
.log(base)
.floor()
.to_isize()
};
// Override digit count if width is specified
if let Some(width) = f.width() {
digits = width as isize;
}
let string = self.format_circle(base, digits);
write!(f, "{}", string)
}
}
impl<
F: Integer
+ FullInt
+ Shl<isize, Output = F>
+ Shr<isize, Output = F>
+ Shl<F, Output = F>
+ Shr<F, Output = F>
+ Shl<E, Output = F>
+ Shr<E, Output = F>
+ WrappingNeg
+ WrappingAdd
+ WrappingMul
+ WrappingSub,
E: Integer
+ FullInt
+ Shl<isize, Output = E>
+ Shr<isize, Output = E>
+ Shl<E, Output = E>
+ Shr<E, Output = E>
+ Shl<F, Output = E>
+ Shr<F, Output = E>
+ WrappingNeg
+ WrappingAdd
+ WrappingMul
+ WrappingSub,
> fmt::Debug for Circle<F, E>
where
F: FractionConstants,
E: ExponentConstants,
Circle<F, E>: CircleConstants,
Scalar<F, E>: ScalarConstants,
u8: AsPrimitive<F>,
u16: AsPrimitive<F>,
u32: AsPrimitive<F>,
u64: AsPrimitive<F>,
u128: AsPrimitive<F>,
usize: AsPrimitive<F>,
i8: AsPrimitive<F>,
i16: AsPrimitive<F>,
i32: AsPrimitive<F>,
i64: AsPrimitive<F>,
i128: AsPrimitive<F>,
isize: AsPrimitive<F>,
u8: AsPrimitive<E>,
u16: AsPrimitive<E>,
u32: AsPrimitive<E>,
u64: AsPrimitive<E>,
u128: AsPrimitive<E>,
usize: AsPrimitive<E>,
i8: AsPrimitive<E>,
i16: AsPrimitive<E>,
i32: AsPrimitive<E>,
i64: AsPrimitive<E>,
i128: AsPrimitive<E>,
isize: AsPrimitive<E>,
I256: From<F>,
I256: From<E>,
Scalar<i128, i128>: From<Scalar<F, E>>,
{
/// Formats a Circle for debug output showing internal bit representation.
///
/// # Debug Modes
///
/// - **Plain (`{:?}`)**: Shows raw binary bits as 0s and 1s for both components
/// - **Fancy (`{:#?}`)**: Shows coloured binary with special characters
///
/// # Format
///
/// The output shows: `real_fraction_bits | imaginary_fraction_bits *2^ exponent_bits`
///
/// Both real and imaginary components share the same exponent.
///
/// # Examples
///
/// ```rust
/// use spirix::CircleF5E3;
/// let z = CircleF5E3::new(1, -1);
/// println!("{:?}", z); // Plain binary
/// println!("{:#?}", z); // Coloured with special chars
/// ```
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
// {:#?} - Fancy coloured output
write!(f, "{}", self.format_debug_fancy())
} else {
// {:?} - Plain binary output
write!(f, "{}", self.format_debug_plain())
}
}
}
#[allow(private_bounds)]
impl<
F: Integer
+ FullInt
+ Shl<isize, Output = F>
+ Shr<isize, Output = F>
+ Shl<F, Output = F>
+ Shr<F, Output = F>
+ Shl<E, Output = F>
+ Shr<E, Output = F>
+ WrappingNeg
+ WrappingAdd
+ WrappingMul
+ WrappingSub,
E: Integer
+ FullInt
+ Shl<isize, Output = E>
+ Shr<isize, Output = E>
+ Shl<E, Output = E>
+ Shr<E, Output = E>
+ Shl<F, Output = E>
+ Shr<F, Output = E>
+ WrappingNeg
+ WrappingAdd
+ WrappingMul
+ WrappingSub,
> Circle<F, E>
where
F: FractionConstants,
E: ExponentConstants,
Scalar<F, E>: ScalarConstants,
Circle<F, E>: CircleConstants,
u8: AsPrimitive<F>,
u16: AsPrimitive<F>,
u32: AsPrimitive<F>,
u64: AsPrimitive<F>,
u128: AsPrimitive<F>,
usize: AsPrimitive<F>,
i8: AsPrimitive<F>,
i16: AsPrimitive<F>,
i32: AsPrimitive<F>,
i64: AsPrimitive<F>,
i128: AsPrimitive<F>,
isize: AsPrimitive<F>,
u8: AsPrimitive<E>,
u16: AsPrimitive<E>,
u32: AsPrimitive<E>,
u64: AsPrimitive<E>,
u128: AsPrimitive<E>,
usize: AsPrimitive<E>,
i8: AsPrimitive<E>,
i16: AsPrimitive<E>,
i32: AsPrimitive<E>,
i64: AsPrimitive<E>,
i128: AsPrimitive<E>,
isize: AsPrimitive<E>,
I256: From<F>,
I256: From<E>,
{
/// Core formatting function that converts a Circle to a string representation.
///
/// This function formats both the real and imaginary components using the same
/// **Spirix arithmetic** approach as `Scalar::format_scalar()`. It does NOT
/// convert numbers to u8 or use bitmasks - instead, it extracts digits one at a time
/// using division, multiplication, floor, and subtraction operations.
///
/// # Algorithm
///
/// 1. **Special Values**: Check for undefined, infinity, exploded, vanished, or zero
/// 2. **Mode Selection**: Choose between scientific (big/small) or normal notation
/// 3. **Format Real Component**: Extract digits using Spirix arithmetic
/// 4. **Format Imaginary Component**: Extract digits using Spirix arithmetic
/// 5. **Combine**: Return as `⦇real,imaginary⦈`
///
/// # Parameters
///
/// - `base`: The numeric base (2-36) to use for digit extraction
/// - `digits`: Maximum number of significant digits to display per component
///
/// # Returns
///
/// A string with the format `⦇real,imaginary⦈` for normal values, or special
/// symbols for non-normal values.
///
/// # Key Point
///
/// Just like Scalar formatting, this uses `to_u8()` ONLY for converting
/// already-extracted single digits (0-35) to characters. All digit extraction
/// is done using Spirix division and multiplication.
fn format_circle(&self, base: u8, digits: isize) -> String {
if !self.is_normal() {
if self.is_undefined() {
let prefix = self.real.sa();
return Undefined::from_prefix(prefix).symbol.to_owned();
}
}
let mut string = "⦇".to_owned();
if !self.is_normal() {
if self.is_infinite() {
string.push_str("∞");
} else if self.exploded() {
let direction = self.sign();
let mut mag_r = direction.r().magnitude();
let mut mag_i = direction.i().magnitude();
string.push_str("↑");
let decimal = 1;
if mag_r.is_normal() {
if self.r().is_negative() {
string.push('-');
} else {
string.push('+');
}
for d in 0..digits {
if d == decimal {
string.push('.');
}
let digit = mag_r.to_u8();
if digit < 10 {
string.push(digit.wrapping_add(48) as char)
} else {
string.push(digit.wrapping_add(55) as char);
}
mag_r = mag_r.frac() * base;
}
} else {
string.push('0');
}
string.push(',');
string.push('↑');
if mag_i.is_normal() {
if self.i().is_negative() {
string.push('-');
} else {
string.push('+');
}
for d in 0..digits {
if d == decimal {
string.push('.');
}
let digit = mag_i.to_u8();
if digit < 10 {
string.push(digit.wrapping_add(48) as char)
} else {
string.push(digit.wrapping_add(55) as char);
}
mag_i = mag_i.frac() * base;
}
} else {
string.push('0');
}
} else if self.vanished() {
let direction = self.sign();
let mut mag_r = direction.r().magnitude();
let mut mag_i = direction.i().magnitude();
string.push_str("↓");
let decimal = 1;
if mag_r.is_normal() {
if self.r().is_negative() {
string.push('-');
} else {
string.push('+');
}
for d in 0..digits {
if d == decimal {
string.push('.');
}
let digit = mag_r.to_u8();
if digit < 10 {
string.push(digit.wrapping_add(48) as char)
} else {
string.push(digit.wrapping_add(55) as char);
}
mag_r = mag_r.frac() * base;
}
} else {
string.push('0');
}
string.push('%');
string.push(',');
string.push('↓');
if mag_i.is_normal() {
if self.i().is_negative() {
string.push('-');
} else {
string.push('+');
}
for d in 0..digits {
if d == decimal {
string.push('.');
}
let digit = mag_i.to_u8();
if digit < 10 {
string.push(digit.wrapping_add(48) as char)
} else {
string.push(digit.wrapping_add(55) as char);
}
mag_i = mag_i.frac() * base;
}
} else {
string.push('0');
}
string.push('%');
} else {
string.push('0');
string.push('⦈');
}
} else {
let base_scalar = Scalar::<F, E>::from(base);
// Three-way split: Big (scientific), Normal (decimal), Small (scientific)
if self.r() <= -base_scalar.pow(digits)
|| self.r() >= base_scalar.pow(digits)
|| self.i() <= -base_scalar.pow(digits)
|| self.i() >= base_scalar.pow(digits)
{
if F::FRACTION_BITS < E::EXPONENT_BITS {
match E::EXPONENT_BITS {
16 => string
.push_str(&CircleF4E4::from(self).format_scientific_big(base, digits)),
32 => string
.push_str(&CircleF5E5::from(self).format_scientific_big(base, digits)),
64 => string
.push_str(&CircleF6E6::from(self).format_scientific_big(base, digits)),
128 => string
.push_str(&CircleF7E7::from(self).format_scientific_big(base, digits)),
_ => string.push_str(&self.format_scientific_big(base, digits)),
}
} else {
string.push_str(&self.format_scientific_big(base, digits))
}
} else if self.r().magnitude().max(self.i().magnitude()) < base_scalar.pow(-4) {
if F::FRACTION_BITS < E::EXPONENT_BITS {
match E::EXPONENT_BITS {
16 => string.push_str(
&CircleF4E4::from(self).format_scientific_small(base, digits),
),
32 => string.push_str(
&CircleF5E5::from(self).format_scientific_small(base, digits),
),
64 => string.push_str(
&CircleF6E6::from(self).format_scientific_small(base, digits),
),
128 => string.push_str(
&CircleF7E7::from(self).format_scientific_small(base, digits),
),
_ => string.push_str(&self.format_scientific_small(base, digits)),
}
} else {
string.push_str(&self.format_scientific_small(base, digits))
}
} else {
// Normal notation: use floor to split integer and fractional parts
let real = self.r();
let real_magnitude = real.magnitude();
let mut real_integer = real_magnitude.floor();
let mut real_fraction = real_magnitude - real_integer;
// Extract integer digits using /base
let mut int_digits = Vec::new();
let mut digit_count = 0;
if real_integer.is_zero() {
int_digits.push(0u8);
} else {
let mut leading = true;
while !real_integer.is_zero() && digit_count < digits {
let scaled = real_integer / base_scalar;
real_integer = scaled.floor();
let digit = ((scaled - scaled.floor()) * base_scalar + Scalar::<F, E>::HALF).to_u8();
int_digits.push(digit);
// Only count non-leading digits
if leading && digit == 0 {
// Still leading zeros, don't increment counter
} else {
leading = false;
digit_count = digit_count.wrapping_add(1);
}
}
}
if real.is_negative() {
string.push('-');
} else if real.is_positive() {
string.push('+');
}
// Convert integer part
for &digit in int_digits.iter().rev() {
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
string.push(digit_char);
}
// Handle fractional part if it exists
if !real_fraction.is_zero() {
string.push('.');
while digit_count < digits && !real_fraction.is_zero() {
real_fraction = real_fraction * base_scalar;
let digit = real_fraction.to_u8();
real_fraction = real_fraction - digit;
// Don't count leading fractional zeros
if !(digit == 0 && digit_count == 0) {
digit_count = digit_count.wrapping_add(1);
}
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
string.push(digit_char);
}
}
string.push(',');
let imaginary = self.i();
let imaginary_magnitude = imaginary.magnitude();
let mut imaginary_integer = imaginary_magnitude.floor();
let mut imaginary_fraction = imaginary_magnitude - imaginary_integer;
// Extract integer digits using /base
int_digits = Vec::new();
digit_count = 0;
if imaginary_integer.is_zero() {
int_digits.push(0u8);
} else {
let mut leading = true;
while !imaginary_integer.is_zero() && digit_count < digits {
let scaled = imaginary_integer / base_scalar;
imaginary_integer = scaled.floor();
let digit = ((scaled - scaled.floor()) * base_scalar + Scalar::<F, E>::HALF).to_u8();
int_digits.push(digit);
// Only count non-leading digits
if leading && digit == 0 {
// Still leading zeros, don't increment counter
} else {
leading = false;
digit_count = digit_count.wrapping_add(1);
}
}
}
if imaginary.is_negative() {
string.push('-');
} else if imaginary.is_positive() {
string.push('+');
}
// Convert integer part
for &digit in int_digits.iter().rev() {
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
string.push(digit_char);
}
// Handle fractional part if it exists
if !imaginary_fraction.is_zero() {
string.push('.');
while digit_count < digits && !imaginary_fraction.is_zero() {
imaginary_fraction = imaginary_fraction * base_scalar;
let digit = imaginary_fraction.to_u8();
imaginary_fraction = imaginary_fraction - digit;
// Don't count leading fractional zeros
if !(digit == 0 && digit_count == 0) {
digit_count = digit_count.wrapping_add(1);
}
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
string.push(digit_char);
}
}
string.push('⦈');
}
}
string
}
/// Formats large complex numbers in scientific notation.
///
/// Used when either component's magnitude is greater than or equal to `base^digits`.
/// Both components are scaled by the same exponent to maintain their relative magnitudes.
///
/// # Algorithm
///
/// 1. **Find Unified Scale**: Use the larger of the two component magnitudes
/// 2. **Calculate Exponent**: Take `log_base(max_magnitude).floor()`
/// 3. **Normalize Both**: Divide both components by `base^exponent`
/// 4. **Extract Digits**: Use Spirix arithmetic on each component separately
/// 5. **Add Exponent**: Append `×base^exponent` suffix
///
/// # Unified Scaling
///
/// Unlike formatting two separate Scalars, Circle uses a single shared exponent
/// based on the larger component. This ensures the relative magnitudes of real
/// and imaginary parts are preserved in the output.
///
/// # Output Format
///
/// `⦇±d.ddd...,±d.ddd...⦈×base^±exp`
fn format_scientific_big(&self, base: u8, digits: isize) -> String {
let base_scalar = Scalar::<F, E>::from(base);
// Find the largest component magnitude for unified scaling
let mag_r = if self.r() == Scalar::<F, E>::MIN {
Scalar::<F, E>::MAX
} else {
self.r().magnitude()
};
let mag_i = if self.i() == Scalar::<F, E>::MIN {
Scalar::<F, E>::MAX
} else {
self.i().magnitude()
};
let max_magnitude = mag_r.max(mag_i);
let mut scale = max_magnitude.log(base_scalar).floor();
let mut scaled_r = self.r() / base_scalar.pow(scale);
let mut scaled_i = self.i() / base_scalar.pow(scale);
// Adjust scale to ensure largest component is in range [1, base)
while scaled_r.magnitude().max(scaled_i.magnitude()) >= base_scalar {
scale = scale + 1;
scaled_r = self.r() / base_scalar.pow(scale);
scaled_i = self.i() / base_scalar.pow(scale);
}
while scaled_r.magnitude().max(scaled_i.magnitude()) < 1 {
scale = scale - 1;
scaled_r = self.r() / base_scalar.pow(scale);
scaled_i = self.i() / base_scalar.pow(scale);
}
let mut result = String::new();
if scaled_r.is_negative() {
result.push('-');
scaled_r = -scaled_r;
} else if scaled_r.is_positive() {
result.push('+');
}
for d in 0..digits {
let digit = scaled_r.to_u8();
scaled_r = (scaled_r - digit) * base_scalar;
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
result.push(digit_char);
if scaled_r.is_zero() {
break;
}
if d == 0 {
result.push('.');
}
}
result.push(',');
if scaled_i.is_negative() {
result.push('-');
scaled_i = -scaled_i;
} else if scaled_i.is_positive() {
result.push('+');
}
for d in 0..digits {
let digit = scaled_i.to_u8();
scaled_i = (scaled_i - digit) * base_scalar;
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
result.push(digit_char);
if scaled_i.is_zero() {
break;
}
if d == 0 {
result.push('.');
}
}
result.push('⦈');
// Add scientific notation suffix
if !scale.is_zero() {
result.push('×');
if base < 10 {
result.push(base.wrapping_add(48) as char)
} else {
result.push(base.wrapping_add(55) as char);
}
result.push('^');
if scale.is_negative() {
result.push('-');
// Extract digits from exponent using Spirix arithmetic (avoids saturation)
let mut exp_value = -scale;
let mut exp_digits = Vec::new();
if exp_value.is_zero() {
exp_digits.push(0u8);
} else {
while exp_value.is_normal() && !exp_value.is_zero() {
let scaled = exp_value / base_scalar;
let floored = scaled.floor();
let digit =
((scaled - floored) * base_scalar + Scalar::<F, E>::HALF).to_u8();
exp_digits.push(digit);
exp_value = floored;
}
}
for &digit in exp_digits.iter().rev() {
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
result.push(digit_char);
}
} else {
result.push('+');
// Extract digits from exponent using Spirix arithmetic (avoids saturation)
let mut exp_value = scale;
let mut exp_digits = Vec::new();
if exp_value.is_zero() {
exp_digits.push(0u8);
} else {
while exp_value.is_normal() && !exp_value.is_zero() {
let scaled = exp_value / base_scalar;
let floored = scaled.floor();
let digit =
((scaled - floored) * base_scalar + Scalar::<F, E>::HALF).to_u8();
exp_digits.push(digit);
exp_value = floored;
}
}
for &digit in exp_digits.iter().rev() {
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
result.push(digit_char);
}
}
}
result
}
/// Formats tiny complex numbers in scientific notation.
///
/// Used when both components have magnitude less than `base^-4`.
/// Like `format_scientific_big()`, uses unified scaling for both components.
///
/// # Algorithm
///
/// 1. **Find Unified Scale**: Use the larger of the two component magnitudes
/// 2. **Calculate Exponent**: Take `-log_base(max_magnitude).floor()`
/// 3. **Normalize Both**: Multiply both components by `base^exponent`
/// 4. **Handle Overflow**: If `base^exponent` would explode, use incremental multiplication
/// 5. **Extract Digits**: Use Spirix arithmetic on each component separately
/// 6. **Add Exponent**: Append `×base^-exp` suffix
///
/// # Unified Scaling
///
/// Both components share the same negative exponent to preserve their relative
/// magnitudes in the output, just like `format_scientific_big()`.
///
/// # Output Format
///
/// `⦇±d.ddd...,±d.ddd...⦈×base^-exp`
fn format_scientific_small(&self, base: u8, digits: isize) -> String {
let base_scalar = Scalar::<F, E>::from(base);
// Find the largest component magnitude for unified scaling (same as big numbers)
let mag_r = if self.r() == Scalar::<F, E>::MIN {
Scalar::<F, E>::MAX
} else {
self.r().magnitude()
};
let mag_i = if self.i() == Scalar::<F, E>::MIN {
Scalar::<F, E>::MAX
} else {
self.i().magnitude()
};
let max_magnitude = mag_r.max(mag_i);
let mut power = -max_magnitude.log(base_scalar).floor();
let mut scaled_r;
let mut scaled_i;
if base_scalar.pow(power).exploded() {
while base_scalar.pow(power).exploded() {
power -= 1;
}
scaled_r = self.r() * base_scalar.pow(power);
scaled_i = self.i() * base_scalar.pow(power);
// Use incremental multiplication to get into [1, base) range
while scaled_r.magnitude().max(scaled_i.magnitude()) < 1 {
power += 1;
scaled_r *= base_scalar;
scaled_i *= base_scalar;
}
} else {
// Normal adjustment loops
scaled_r = self.r() * base_scalar.pow(power);
scaled_i = self.i() * base_scalar.pow(power);
while scaled_r.magnitude().max(scaled_i.magnitude()) >= base_scalar {
power -= 1;
scaled_r = self.r() * base_scalar.pow(power);
scaled_i = self.i() * base_scalar.pow(power);
}
while scaled_r.magnitude().max(scaled_i.magnitude()) < 1 {
power += 1;
scaled_r = self.r() * base_scalar.pow(power);
scaled_i = self.i() * base_scalar.pow(power);
}
}
let mut result = String::new();
if scaled_r.is_negative() {
result.push('-');
scaled_r = -scaled_r;
} else if scaled_r.is_positive() {
result.push('+');
}
for d in 0..digits {
let digit = scaled_r.to_u8();
scaled_r = (scaled_r - digit) * base_scalar;
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
result.push(digit_char);
if scaled_r.is_zero() {
break;
}
if d == 0 {
result.push('.');
}
}
result.push(',');
if scaled_i.is_negative() {
result.push('-');
scaled_i = -scaled_i;
} else if scaled_i.is_positive() {
result.push('+');
}
for d in 0..digits {
let digit = scaled_i.to_u8();
scaled_i = (scaled_i - digit) * base_scalar;
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
result.push(digit_char);
if scaled_i.is_zero() {
break;
}
if d == 0 {
result.push('.');
}
}
result.push('⦈');
// Add scientific notation suffix
if !power.is_zero() {
result.push('×');
if base < 10 {
result.push(base.wrapping_add(48) as char)
} else {
result.push(base.wrapping_add(55) as char);
}
result.push('^');
result.push('-');
// Extract digits from exponent using Spirix arithmetic (avoids saturation)
let mut exp_value = power;
let mut exp_digits = Vec::new();
if exp_value.is_zero() {
exp_digits.push(0u8);
} else {
while exp_value.is_normal() && !exp_value.is_zero() {
let scaled = exp_value / base_scalar;
let floored = scaled.floor();
let digit = ((scaled - floored) * base_scalar + Scalar::<F, E>::HALF).to_u8();
exp_digits.push(digit);
exp_value = floored;
}
}
for &digit in exp_digits.iter().rev() {
let digit_char = if digit < 10 {
digit.wrapping_add(b'0') as char
} else {
digit.wrapping_sub(10).wrapping_add(b'A') as char
};
result.push(digit_char);
}
}
result
}
/// Formats the Circle as plain binary for debug output (`{:?}`).
///
/// Shows the raw bit representation of both fraction components and the shared exponent.
/// Unlike display formatting which uses arithmetic, debug formatting directly inspects
/// the bits using `rotate_left()`.
///
/// # Output Format
///
/// `real_fraction_bits | imaginary_fraction_bits *2^ exponent_bits`
///
/// Where:
/// - `real_fraction_bits`: Binary representation of the real component's fraction (0s and 1s)
/// - `imaginary_fraction_bits`: Binary representation of the imaginary component's fraction
/// - `exponent_bits`: Binary representation of the shared exponent field
/// - Bits are shown from MSB to LSB (most significant first)
/// - Spaces are added every 8 bits for readability
/// - Double space in the middle of each fraction component (except for 8-bit fractions)
fn format_debug_plain(&self) -> String {
let mut binary = String::new();
let middle = F::FRACTION_BITS / 2;
// Format real component bits
let mut rotating_real = self.real;
for b in 0..F::FRACTION_BITS {
if F::FRACTION_BITS != 8 && b == middle {
binary.push_str(" "); // Double space in middle
}
binary.push(if rotating_real.is_negative() {
'1'
} else {
'0'
});
rotating_real = rotating_real.rotate_left(1);
if b % 8 == 7 || b == 0 {
binary.push(' ');
}
}
binary.push_str("| ");
// Format imaginary component bits
let mut rotating_imag = self.imaginary;
for b in 0..F::FRACTION_BITS {
if F::FRACTION_BITS != 8 && b == middle {
binary.push_str(" "); // Double space in middle
}
binary.push(if rotating_imag.is_negative() {
'1'
} else {
'0'
});
rotating_imag = rotating_imag.rotate_left(1);
if b % 8 == 7 || b == 0 {
binary.push(' ');
}
}
binary.push_str(" *2^ ");
// Format exponent bits
let mut exp_rotating = self.exponent;
for b in 0..E::EXPONENT_BITS {
binary.push(if exp_rotating.is_negative() { '1' } else { '0' });
exp_rotating = exp_rotating.rotate_left(1);
if b % 8 == 7 || b == 0 {
binary.push(' ');
}
}
binary
}
/// Formats the Circle with colours and special characters for debug output (`{:#?}`).
///
/// Similar to `format_debug_plain()`, but with ANSI colour codes and Unicode characters
/// that indicate each component's state visually.
///
/// # Visual Elements
///
/// - **Colours**: Each component gets its own colour based on its state:
/// - Real component: Coloured based on real value's state
/// - Imaginary component: Coloured based on imaginary value's state
/// - Exponent: Coloured based on sign (integer/fractional)
/// - **Characters**: Same as Scalar debug formatting:
/// - Normal: □ (unset bit), ■ (set bit)
/// - Undefined: ▵ (unset bit), ▴ (set bit)
/// - Zero: 0 (unset bit), | (set bit)
/// - Other: ○ (unset bit), ● (set bit)
///
/// # ANSI Colour Format
///
/// Uses `\x1B[38;2;R;G;Bm` for 24-bit RGB colours and `\x1B[0m` for reset.
fn format_debug_fancy(&self) -> String {
let mut binary = String::new();
let middle = F::FRACTION_BITS / 2;
let (unset, set) = self.get_binary_chars();
// Format real component with appropriate colour
let real_scheme = self.get_real_colour_scheme();
let real_rgb = &real_scheme.colour;
binary.push_str(&format!(
"\x1B[38;2;{};{};{}m",
real_rgb[0], real_rgb[1], real_rgb[2]
));
let mut rotating_real = self.real;
for b in 0..F::FRACTION_BITS {
if F::FRACTION_BITS != 8 && b == middle {
binary.push(' ');
}
binary.push(if rotating_real.is_negative() {
set
} else {
unset
});
rotating_real = rotating_real.rotate_left(1);
if b % 8 == 7 || b == 0 {
binary.push(' ');
}
}
binary.push_str("\x1B[0m| ");
// Format imaginary component with appropriate colour
let imag_scheme = self.get_imag_colour_scheme();
let imag_rgb = &imag_scheme.colour;
binary.push_str(&format!(
"\x1B[38;2;{};{};{}m",
imag_rgb[0], imag_rgb[1], imag_rgb[2]
));
let mut rotating_imag = self.imaginary;
for b in 0..F::FRACTION_BITS {
if F::FRACTION_BITS != 8 && b == middle {
binary.push(' ');
}
binary.push(if rotating_imag.is_negative() {
set
} else {
unset
});
rotating_imag = rotating_imag.rotate_left(1);
if b % 8 == 7 || b == 0 {
binary.push(' ');
}
}
binary.push_str("\x1B[0m *2^ ");
// Format exponent bits with their colour
let exp_scheme = if self.exponent.is_negative() {
&COLOURS.fractional_exponent
} else if self.exponent.is_positive() {
&COLOURS.integer_exponent
} else {
&COLOURS.zero
};
binary.push_str(&format!(
"\x1B[38;2;{};{};{}m",
exp_scheme.colour[0], exp_scheme.colour[1], exp_scheme.colour[2]
));
let mut exp_rotating = self.exponent;
for b in 0..E::EXPONENT_BITS {
binary.push(if exp_rotating.is_negative() {
'■'
} else {
'□'
});
exp_rotating = exp_rotating.rotate_left(1);
if b % 8 == 7 || b == 0 {
binary.push(' ');
}
}
binary.push_str("\x1B[0m");
binary
}
/// Selects the appropriate colour scheme for the real component.
///
/// Used by `format_debug_fancy()` to choose the right colour for the real fraction bits.
///
/// # Returns
///
/// A reference to the appropriate `ColourScheme` from the global `COLOURS` palette.
fn get_real_colour_scheme(&self) -> &'static ColourScheme {
if self.is_normal() {
if self.real.is_negative() {
&COLOURS.normal_negative
} else {
&COLOURS.normal_positive
}
} else if self.is_undefined() {
&COLOURS.undefined
} else if self.vanished() {
if self.real.is_negative() {
&COLOURS.vanished_negative
} else {
&COLOURS.vanished_positive
}
} else if self.exploded() {
if self.real.is_negative() {
&COLOURS.exploded_negative
} else {
&COLOURS.exploded_positive
}
} else {
&COLOURS.zero
}
}
/// Selects the appropriate colour scheme for the imaginary component.
///
/// Used by `format_debug_fancy()` to choose the right colour for the imaginary fraction bits.
///
/// # Returns
///
/// A reference to the appropriate `ColourScheme` from the global `COLOURS` palette.
fn get_imag_colour_scheme(&self) -> &'static ColourScheme {
if self.is_normal() {
if self.imaginary.is_negative() {
&COLOURS.normal_negative
} else {
&COLOURS.normal_positive
}
} else if self.is_undefined() {
&COLOURS.undefined
} else if self.vanished() {
if self.imaginary.is_negative() {
&COLOURS.vanished_negative
} else {
&COLOURS.vanished_positive
}
} else if self.exploded() {
if self.imaginary.is_negative() {
&COLOURS.exploded_negative
} else {
&COLOURS.exploded_positive
}
} else {
&COLOURS.zero
}
}
/// Selects the appropriate Unicode characters for representing bits.
///
/// Used by `format_debug_fancy()` to choose special characters based on the Circle's state.
///
/// # Returns
///
/// A tuple of `(unset_char, set_char)` representing 0 and 1 bits respectively.
fn get_binary_chars(&self) -> (char, char) {
if self.is_normal() {
('□', '■')
} else if self.is_undefined() {
('▵', '▴')
} else if self.is_zero() {
('0', '|')
} else {
('○', '●')
}
}
}