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
use std::ops::{Add,Sub,Mul,Div,AddAssign,SubAssign,MulAssign,DivAssign,Neg,Rem};

use crate::ParsingStandardFormError;

/// Represents a number in standard form.
///
/// The `Standardform` struct holds the significand (mantissa) of the number 
/// and an exponent that determines the power of 10 by which the significand should be multiplied.
#[derive(Clone,PartialEq)]
pub struct StandardForm  {
    mantissa : f64,
    exponent : i8 
}

impl StandardForm {
    /// Creates a new instance of `StandardForm` with the given mantissa and exponent.
    ///
    /// This constructor initializes a new `StandardForm` instance with the provided `mantissa` and `exponent`.
    /// It's important to note that the provided `mantissa` and `exponent` may not be exactly the same as the
    /// values stored in the resulting instance. The values are adjusted automatically to adhere to the rules
    /// of standard form representation, ensuring the most appropriate form for the given input.
    /// 
    ///  ## Rules :
    /// If the current mantissa and exponent do not satisfy the standard form representation requirements,
    /// this method will adjust them while maintaining the value of the number represented. The adjustment
    /// ensures that the mantissa is between 1 (inclusive) and 10 (exclusive) and the exponent is such that
    /// the product of mantissa and 10 raised to the exponent yields the original number.
    pub fn new(mantissa : f64,exponent : i8) -> Self {
        let mut instance = Self::new_unchecked(mantissa,exponent);
        instance.adjust();
        instance
    }

    pub(crate) fn new_unchecked(mantissa : f64,exponent : i8) -> Self { 
        Self { mantissa , exponent }
    }

    fn in_range(&self) -> bool {
        (self.mantissa >= 1.0 && self.mantissa <= 10.0) || (self.mantissa >= -10.0 && self.mantissa <= -1.0)
    }

    fn adjust(&mut self) {
        if self.in_range() || self.mantissa == 0.0 {
            return;
        }

        // means its things like 0.2323 not -700
        match self.mantissa > -1.0 && self.mantissa < 1.0 {
            true => while !self.in_range() {
                self.mantissa *= 10.0;
                self.exponent -= 1; 
            },
            false => while !self.in_range() {
                self.mantissa /= 10.0;
                self.exponent += 1; 
            }
        }
    }
}

impl StandardForm {
    /// Returns a reference to the StandardForm representing the significand (mantissa) of the number.
    pub const fn mantissa(&self) -> &f64 {
        &self.mantissa
    }

    /// Returns the exponent that determines the power of 10 by which the significand should be multiplied.
    pub const fn exponent(&self) -> &i8 {
        &self.exponent
    }    
}

impl StandardForm {
    /// Returns the string representation of the number in scientific notation.
    pub fn to_scientific_notation(&self) -> String {
        format!("{}e{}", self.mantissa, self.exponent)
    }
        
    /// Returns the string representation of the number in engineering notation.
    pub fn to_engineering_notation(&self) -> String {
        format!("{}*10^{}", self.mantissa, self.exponent)
    }    
}

impl Default for StandardForm {
    fn default() -> Self {
        Self { mantissa : 1.0, exponent : 0 }
    }
}

impl PartialOrd for StandardForm {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        match self.exponent == other.exponent {
            true => self.mantissa.partial_cmp(&other.mantissa),
            false => self.exponent.partial_cmp(&other.exponent)
        }
    }
}

impl std::fmt::Display for StandardForm {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        if self.exponent > 4 {
            return write!(f,"{}",self.to_scientific_notation());
        };

        write!(f,"{}",self.mantissa * 10_i32.pow(self.exponent as u32) as f64)
    }
}

impl std::fmt::Debug for StandardForm {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f,"{}",self.to_string())
    }
}

impl TryFrom<&str> for StandardForm {
    type Error = ParsingStandardFormError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        if let Ok(number) = value.parse::<f64>() {
            return Ok(number.into());
        }

        if let Some(index) = value.find('e') {
            let m_str : f64 = value[0..index].parse()?;
            let e_str : i8 = value[index + 1..].parse()?;
            return Ok(StandardForm::new(m_str,e_str));
        }
        
        if let Some(index) = value.find('^') {
            let m_str : f64 = value[0..index - 2].parse()?;
            let e_str : i8 = value[index + 1..].parse()?;
            return Ok(StandardForm::new(m_str,e_str));
        }

        Err(ParsingStandardFormError::InvalidFormat)
    }
}

impl TryFrom<&[u8]> for StandardForm {
    type Error = ParsingStandardFormError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        Self::try_from(std::str::from_utf8(value)?)
    }
}

impl Neg for StandardForm {
    type Output = Self;
    fn neg(self) -> Self::Output {
        Self::new_unchecked(-self.mantissa,self.exponent)
    }
}

impl Rem for StandardForm {
    type Output = Self;
    fn rem(self,other : Self) -> Self::Output {
        self.clone() - (self / other.clone() * other) 
    }
}


impl Add for StandardForm {
    type Output = Self;
    fn add(self, other: Self) -> Self {
        let max_power = self.exponent.max(other.exponent);
        let num_sum = self.mantissa * 10.0_f64.powf((self.exponent - max_power) as f64) + other.mantissa * 10.0_f64.powf((other.exponent - max_power) as f64);
        StandardForm::new(num_sum, max_power)
    }
}

impl AddAssign for StandardForm {
    fn add_assign(&mut self, other: Self) {
        let max_power = self.exponent.max(other.exponent);
        let num_sum = self.mantissa * 10.0_f64.powf((self.exponent - max_power) as f64) + other.mantissa * 10.0_f64.powf((other.exponent - max_power) as f64);

        self.mantissa = num_sum;
        self.exponent = max_power;

        self.adjust();
    }
}

impl Sub for StandardForm {
    type Output = Self;
    fn sub(self, other: Self) -> Self {
        let min = self.exponent.min(other.exponent);

        let x = self.mantissa * 10_i32.pow((self.exponent - min) as u32) as f64;
        let y = other.mantissa * 10_i32.pow((other.exponent - min) as u32) as f64;

        let result = x - y;
        let rounded = (result * 1.0e6).round() / 1.0e6;

        StandardForm::new(rounded,min)
    }
}

impl SubAssign for StandardForm {
    fn sub_assign(&mut self, other: Self) {
        let min = self.exponent.min(other.exponent);

        let x = self.mantissa * 10_i32.pow((self.exponent - min) as u32) as f64;
        let y = other.mantissa * 10_i32.pow((other.exponent - min) as u32) as f64;

        let result = x - y;
        let rounded = (result * 1.0e6).round() / 1.0e6;

        self.mantissa = rounded;
        self.exponent = min;
        self.adjust(); 
    }
}

impl Mul for StandardForm {
    type Output = Self;
    fn mul(self, other: Self) -> Self {
        let exponent = self.exponent + other.exponent;
        let mantissa = self.mantissa * other.mantissa;
        let rounded = (mantissa * 1.0e6).round() / 1.0e6;
        StandardForm::new(rounded,exponent)
    }
}

impl MulAssign for StandardForm {
    fn mul_assign(&mut self, other: Self) {
        let exponent = self.exponent + other.exponent;
        let mantissa = self.mantissa * other.mantissa;
        let rounded = (mantissa * 1.0e6).round() / 1.0e6;

        self.mantissa = rounded;
        self.exponent = exponent;

        self.adjust();
    }
}

impl Div for StandardForm {
    type Output = Self;
    fn div(self, other: Self) -> Self {
        StandardForm::new(self.mantissa / other.mantissa,self.exponent - other.exponent)
    }
}

impl DivAssign for StandardForm {
    fn div_assign(&mut self, other: Self) {
        self.mantissa /= other.mantissa;
        self.exponent /= other.exponent;
        self.adjust();
    }
}

macro_rules! primitives {
    (form => $($t:ty),*) => {
        $(
            impl From<$t> for StandardForm {
                fn from(value: $t) -> Self {
                    StandardForm::new(value as f64,0)
                }
            }
        )*
    };

    (eq => $($t:ty),*) => {
        $(
            impl PartialEq<$t> for StandardForm {
                fn eq(&self,other: &$t) -> bool {
                    let rhs : Self = (*other).into();
                    *self == rhs
                }
            }
        )*
    };
    (ord => $($t:ty),*) => {
        $(
            impl PartialOrd<$t> for StandardForm {
                fn partial_cmp(&self, other: &$t) -> Option<std::cmp::Ordering> {
                    let rhs : Self = (*other).into();
                    self.partial_cmp(&rhs)
                }
            }
        )*
    };


    (add => $($t : ty),*) => {
        $(
            impl Add<$t> for StandardForm {
                type Output = Self;
                fn add(self, other: $t) -> Self {
                    let rhs : Self = other.into();
                    self + rhs
                }
            }
            
            impl AddAssign<$t> for StandardForm {
                fn add_assign(&mut self, other: $t) {
                    let rhs : Self = other.into();
                    *self += rhs;
                }
            }
        )*
    };

    (sub => $($t : ty),*) => {
        $(
            impl Sub<$t> for StandardForm {
                type Output = Self;
                fn sub(self, other: $t) -> Self {
                    let rhs : Self = other.into();
                    self - rhs
                }
            }
            
            impl SubAssign<$t> for StandardForm {
                fn sub_assign(&mut self, other: $t) {
                    let rhs : Self = other.into();
                    *self -= rhs;
                }
            }
        )*
    };
    (mul => $($t : ty),*) => {
        $(
            impl Mul<$t> for StandardForm {
                type Output = Self;
                fn mul(self, other: $t) -> Self {
                    let rhs : Self = other.into();
                    self * rhs
                }
            }
            
            impl MulAssign<$t> for StandardForm {
                fn mul_assign(&mut self, other: $t) {
                    let rhs : Self = other.into();
                    *self *= rhs;
                }
            }
        )*
    };
    (div => $($t : ty),*) => {
        $(
            impl Div<$t> for StandardForm {
                type Output = Self;
                fn div(self, other: $t) -> Self {
                    let rhs : Self = other.into();
                    self / rhs
                }
            }
            
            impl DivAssign<$t> for StandardForm {
                fn div_assign(&mut self, other: $t) {
                    let rhs : Self = other.into();
                    *self /= rhs;
                }
            }
        )*
    };
    (operations => $($t:ty),*) => {
        $(
            primitives!(add => $t);
            primitives!(sub => $t);
            primitives!(mul => $t);
            primitives!(div => $t);
        )*
    }
}

primitives!(operations => i8, i16, i32, i64, u8, u16, u32, u64,f32,f64);
primitives!(form => u8,u16,u32,u64,i8,i16,i32,i64,f32,f64);
primitives!(eq => u8,u16,u32,u64,i8,i16,i32,i64,f32,f64);
primitives!(ord => u8,u16,u32,u64,i8,i16,i32,i64,f32,f64);


#[cfg(test)]
mod tests {
    use super::*;
    use std::cmp::Ordering;

    #[test]
    fn assignment_issue() {
        let sf1 = StandardForm::new(1.0,5);
        assert_eq!(*sf1.mantissa(),1.0);
        assert_eq!(*sf1.exponent(),5);
    }

    #[test]
    fn from_u8_standardform(){
        let n = 2u8;
        let r : StandardForm = n.into();

        assert_eq!(r,StandardForm { mantissa : 2.0,exponent : 0 });
    }

    #[test]
    fn test_normalize_with_valid_range() {
        let mut sf = StandardForm::new(2.5, 3);
        sf.adjust();
        assert_eq!(sf.mantissa, 2.5);
        assert_eq!(sf.exponent, 3);
    }

    #[test]
    fn test_normalize_with_invalid_range() {
        let mut sf = StandardForm::new(20.0, 3);
        sf.adjust();
        assert_eq!(sf.mantissa, 2.0);
        assert_eq!(sf.exponent, 4);
    }

    #[test]
    fn test_normalize_with_small_mantissa() {
        let mut sf = StandardForm::new(-0.25, 2);
        sf.adjust();
        assert_eq!(sf.mantissa, -2.5);
        assert_eq!(sf.exponent, 1);
    }

    #[test]
    fn test_normalize_with_large_negative_mantissa() {
        let mut sf = StandardForm::new(-750.0, 4);
        sf.adjust();
        assert_eq!(sf.mantissa, -7.5);
        assert_eq!(sf.exponent, 6);
    }

    #[test]
    fn addition() {
        // Test addition between StandardForm instances
        let a = StandardForm::new(1.2, 3);
        let b = StandardForm::new(3.4, 2);
        let result = a + b;
        assert_eq!(result, StandardForm::new(1.54,3) );
    }

    #[test]
    fn addition_u8() {
        // Test addition with u8
        let a = StandardForm::new(1.0, 1);
        let b = 2u8;
        let result = a + b;
        assert_eq!(result, StandardForm::new(1.2,1));
    }

    #[test]
    fn test_subtraction() {
        // Test subtraction between StandardForm instances
        let a = StandardForm::new(4.6, 2);
        let b = StandardForm::new(3.4, 2);
        let result = a - b;
        assert_eq!(result, StandardForm::new(1.2,2));
    }

    #[test]
    fn multiplication() {
        // Test multiplication between StandardForm instances
        let a = StandardForm::new(1.2, 3);
        let b = StandardForm::new(3.0, 2);
        let result = a * b;
        assert_eq!(result.mantissa, 3.6);
        assert_eq!(result.exponent, 5);
    }

    #[test]
    fn multiplication_u8() {
        // Test multiplication with u8
        let a = StandardForm::new(1.0, 1);        
        let b = 2u8;
        let result = a * b;
        assert_eq!(result.mantissa, 2.0);
        assert_eq!(result.exponent, 1);
    }

    #[test]
    fn division() {
        // Test division between StandardForm instances
        let a = StandardForm::new(4.0, 2);
        let b = StandardForm::new(2.0, 1);
        let result = a / b;
        assert_eq!(result.mantissa, 2.0);
        assert_eq!(result.exponent, 1);
    }

    #[test]
    fn division_u8() {
        // Test division with u8
        let a = StandardForm::new(2.0, 1);
        let b = 2u8;
        let result = a / b;
        assert_eq!(result.mantissa, 1.0);
        assert_eq!(result.exponent, 1);
    }


    #[test]
    fn add_assign() {
        let mut a = StandardForm::new(1.0, 1);
        let b = StandardForm::new(2.0, 1);
        a += b;
        assert_eq!(a.mantissa, 3.0);
        assert_eq!(a.exponent, 1);
    }

    #[test]
    fn add_assign_u8() {
        // Test AddAssign with u8
        let mut a = StandardForm::new(1.0, 1);

        let b = 2u8;

        a += b;
        assert_eq!(a.mantissa, 1.2);
        assert_eq!(a.exponent, 1);
    }

    #[test]
    fn test_partial_cmp_equal() {
        let sf1 = StandardForm::new(1.23, 3);
        let sf2 = StandardForm::new(1.23, 3);

        assert_eq!(sf1.partial_cmp(&sf2), Some(Ordering::Equal));
    }

    #[test]
    fn test_partial_cmp_greater() {

        //300
        let sf1 = StandardForm::new(3.0, 2);
        // 250
        let sf2 = StandardForm::new(2.5, 2);

        assert_eq!(sf1.partial_cmp(&sf2), Some(Ordering::Greater));
    }

    #[test]
    fn test_partial_cmp_less() {
        let sf1 = StandardForm::new(2.5, 2);
        let sf2 = StandardForm::new(3.0, 2);

        assert_eq!(sf1.partial_cmp(&sf2), Some(Ordering::Less));
    }

    #[test]
    fn test_partial_cmp_different_exponents() {
        let sf1 = StandardForm::new(1.5, 2);
        let sf2 = StandardForm::new(1.5, 3);

        // When exponents are different, the comparison is based on the magnitude
        assert_eq!(sf1.partial_cmp(&sf2), Some(Ordering::Less));
    }

    #[test]
    fn test_partial_cmp_zero() {
        let sf1 = StandardForm::new(0.0, 0);
        let sf2 = StandardForm::new(0.0, 0);

        assert_eq!(sf1.partial_cmp(&sf2), Some(Ordering::Equal));
    }

    #[test]
    fn test_partial_cmp_mixed_sign() {
        let sf1 = StandardForm::new(-1.0, 2);
        let sf2 = StandardForm::new(1.0, 2);

        // Negative numbers are considered less than positive numbers with the same magnitude
        assert_eq!(sf1.partial_cmp(&sf2), Some(Ordering::Less));
    }
}