qfall-math 0.1.1

Mathematical foundations for rapid prototyping of lattice-based cryptography
Documentation
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
// Copyright © 2023 Sven Moog, Marcel Luca Schmidt
//
// This file is part of qFALL-math.
//
// qFALL-math is free software: you can redistribute it and/or modify it under
// the terms of the Mozilla Public License Version 2.0 as published by the
// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.

//! Implementations to create a [`Z`] value from other types.
//!
//! The explicit functions contain the documentation.

use super::Z;
use crate::{
    error::{MathError, StringConversionError},
    integer_mod_q::Modulus,
    macros::for_others::implement_empty_trait_owned_ref,
    traits::AsInteger,
};
use flint_sys::fmpz::{fmpz, fmpz_get_si, fmpz_get_ui, fmpz_init_set, fmpz_set_str, fmpz_setbit};
use std::{ffi::CString, str::FromStr};

impl Z {
    /// Creates an Integer that can grow arbitrary large.
    ///
    /// Parameters:
    /// - `value`: the initial value the integer should have
    ///
    /// Returns a new [`Z`] from the [`fmpz`] instance.
    ///
    /// # Safety
    /// Since the parameter is a reference, it still has to be
    /// properly cleared outside this function.
    /// For example, by the drop trait of [`Z`].
    ///
    /// # Examples
    /// ```compile_fail
    /// use qfall_math::integer::Z;
    ///
    /// let z = Z::from(0);
    ///
    /// let a: Z = Z::from_fmpz_ref(&z.value);
    /// ```
    /// ```compile_fail
    /// use qfall_math::integer::Z;
    /// use flint_sys::fmpz::{fmpz, fmpz_clear};
    ///
    /// let value = fmpz(0);
    ///
    /// let a: Z = Z::from_fmpz_ref(&value);
    ///
    /// unsafe{fmpz_clear(&mut value)}
    /// ```
    pub(crate) fn from_fmpz_ref(value: &fmpz) -> Self {
        let mut out = Z::default();
        unsafe {
            fmpz_init_set(&mut out.value, value);
        }
        out
    }

    /// Creates an Integer that can grow arbitrary large.
    ///
    /// Parameters:
    /// - `value`: the initial value the integer should have
    ///
    /// Returns a new [`Z`] from the [`fmpz`] instance.
    ///
    /// # Safety
    /// This function takes ownership. The caller has to ensure that the [`fmpz`]
    /// is not dropped somewhere else. This means that calling this function
    /// with an [`fmpz`] that is wrapped in a different data type is not allowed.
    ///
    /// # Examples
    /// ```compile_fail
    /// use qfall_math::integer::Z;
    /// use flint_sys::fmpz::fmpz;
    ///
    /// let value = fmpz(0);
    ///
    /// let a: Z = Z::from_fmpz(value);
    /// ```
    #[allow(dead_code)]
    pub(crate) unsafe fn from_fmpz(value: fmpz) -> Self {
        Z { value }
    }

    /// Creates a [`Z`] integer from a [`String`]. This function takes a
    /// base between `2` and `62` in which the number is represented.
    ///
    /// Parameters:
    /// - `s`: the integer value as a string
    /// - `base`: the base in which the integer is represented
    ///
    /// Returns a [`Z`] or an error if the provided string was not formatted
    /// correctly, the provided string contains a `Null` byte or the base is out of bounds.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer::Z;
    ///  
    /// let a: Z = Z::from_str_b("100", 2).unwrap();
    /// assert_eq!(Z::from(4), a);
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`OutOfBounds`](MathError::OutOfBounds) if the
    ///   base is not between `2` and `62`.
    /// - Returns a [`MathError`] of type
    ///   [`StringConversionError`](MathError::StringConversionError)
    ///     - if the provided string contains a `Null` byte, or
    ///     - if the provided string was not formatted correctly.
    pub fn from_str_b(s: &str, base: i32) -> Result<Self, MathError> {
        if !(2..=62).contains(&base) {
            return Err(MathError::OutOfBounds(
                "between 2 and 62".to_owned(),
                base.to_string(),
            ));
        }

        if s.contains(char::is_whitespace) {
            return Err(StringConversionError::InvalidStringToZInput(s.to_owned()))?;
        }

        // since |value| = |0| < 62 bits, we do not need to free the allocated space manually
        let mut value: fmpz = fmpz(0);

        let c_string = CString::new(s)?;

        // -1 is returned if the string is an invalid input.
        // Given the documentation `c_string.as_ptr()` is freed once c_string is deallocated
        // 'The pointer will be valid for as long as `self` is'
        // For reading more look at the documentation of `.as_ptr()`.
        match unsafe { fmpz_set_str(&mut value, c_string.as_ptr(), base) } {
            0 => Ok(Z { value }),
            _ => Err(StringConversionError::InvalidStringToZInput(s.to_owned()))?,
        }
    }

    /// Creates a [`Z`] integer from an iterable of [`u8`]s, i.e. a vector of bytes.
    /// This function can only construct positive or zero integers, but not negative ones.
    /// The inverse function to [`Z::from_bytes`] is [`Z::to_bytes`] for positive numbers including `0`.
    ///
    /// Parameters:
    /// - `bytes`: specifies an iterable of bytes that should be set in the new [`Z`] instance.
    ///   The first byte should be the least significant byte, i.e. its first bit the
    ///   least significant bit.
    ///
    /// Returns a [`Z`] with the value provided by the byte iterable.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer::Z;
    /// // instantiate a byte-vector corresponding to "100000001"
    /// // vec![0x01, 0x01] would also be sufficient
    /// let bytes: Vec<u8> = vec![1, 1];
    ///  
    /// let a: Z = Z::from_bytes(&bytes);
    /// assert_eq!(Z::from(257), a);
    /// ```
    pub fn from_bytes(bytes: &[u8]) -> Self {
        let mut res = Z::ZERO;
        for (i, byte) in bytes.iter().enumerate() {
            for j in 0..u8::BITS {
                // if j-th bit of `byte` is `1`, then set `i*8 + j`-th bit in fmpz to `1`
                if ((byte >> j) & 1) % 2 == 1 {
                    unsafe { fmpz_setbit(&mut res.value, (i as u32 * u8::BITS + j) as u64) };
                }
            }
        }
        res
    }

    /// Creates a [`Z`] integer from an iterable of [`bool`]s, i.e. a vector of bits.
    /// This function can only construct positive or zero integers, but not negative ones.
    ///
    /// Parameters:
    /// - `bits`: specifies an iterable of bits that should be set in the new [`Z`] instance.
    ///   The first bit should be the least significant bit.
    ///
    /// Returns a [`Z`] with the value provided by the bit iterable.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer::Z;
    /// // instantiate a bit-vector corresponding to "101"
    /// let bits: Vec<bool> = vec![true, false, true];
    ///  
    /// let a: Z = Z::from_bits(&bits);
    /// assert_eq!(Z::from(5), a);
    /// ```
    pub fn from_bits(bits: &[bool]) -> Z {
        let mut value = Z::default();
        for (i, bit) in bits.iter().enumerate() {
            if *bit {
                unsafe { fmpz_setbit(&mut value.value, i as u64) };
            }
        }
        value
    }

    /// Create a [`Z`] integer from a [`String`], i.e. its UTF8-Encoding.
    /// This function can only construct positive or zero integers, but not negative ones.
    /// The inverse of this function is [`Z::to_utf8`].
    ///
    /// Parameters:
    /// - `message`: specifies the message that is transformed via its UTF8-Encoding
    ///   to a new [`Z`] instance.
    ///
    /// Returns a [`Z`] with corresponding value to the message's UTF8-Encoding.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer::Z;
    /// let message = "hello!";
    ///  
    /// let value = Z::from_utf8(&message);
    /// assert_eq!(Z::from(36762444129640u64), value);
    /// ```
    pub fn from_utf8(message: &str) -> Z {
        Z::from_bytes(message.as_bytes())
    }
}

/// A trait that indicates for which types the `From for Z` should be implemented.
/// It is used as a workaround to implement the [`From`] trait without colliding
/// with the default implementation for [`Z`] and also to filter out [`Zq`](crate::integer_mod_q::Zq).
trait IntoZ {}
impl IntoZ for &Z {}
implement_empty_trait_owned_ref!(IntoZ for Modulus fmpz u8 u16 u32 u64 i8 i16 i32 i64);

impl<Integer: AsInteger + IntoZ> From<Integer> for Z {
    /// Converts an integer to [`Z`].
    ///
    /// Parameters:
    /// `value`: must be a rust integer, [`Modulus`], or a reference of these types.
    ///
    /// Returns a [`Z`] with the value specified in the parameter.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer::Z;
    ///
    /// let a = Z::from(10);
    /// let b = Z::from(i64::MAX);
    /// let c = Z::from(&u64::MAX);
    /// ```
    fn from(value: Integer) -> Self {
        match value.get_fmpz_ref() {
            Some(val) => Z::from_fmpz_ref(val),
            None => unsafe {
                let value = value.into_fmpz();
                Z { value }
            },
        }
    }
}

impl FromStr for Z {
    type Err = MathError;

    /// Creates a [`Z`] integer from a [`String`].
    ///
    /// Parameters:
    /// - `s`: the integer value of form: `"12"` for the number 12 and `"-12"` for -12.
    ///
    /// Returns a [`Z`] or an error if the provided string was not formatted
    /// correctly, or the provided string contains a `Null` byte.
    ///
    /// # Examples
    /// ```
    /// use std::str::FromStr;
    /// use qfall_math::integer::Z;
    ///  
    /// let a: Z = "100".parse().unwrap();
    /// let b: Z = Z::from(100);
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type
    ///   [`StringConversionError`](MathError::StringConversionError)
    ///     - if the provided string contains a `Null` byte, or
    ///     - if the provided string was not formatted correctly.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Z::from_str_b(s, 10)
    }
}

impl TryFrom<&Z> for i64 {
    type Error = MathError;

    /// Converts a [`Z`] into an [`i64`]. If the value is either too large
    /// or too small an error is returned.
    ///
    /// Parameters:
    /// - `value`: the value that will be converted into an [`i64`]
    ///
    /// Returns the value as an [`i64`] or an error if it does not fit
    /// into an [`i64`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer::Z;
    ///
    /// let max = Z::from(i64::MAX);
    /// assert_eq!(i64::MAX, i64::try_from(&max).unwrap());
    ///
    /// let max = Z::from(u64::MAX);
    /// assert!(i64::try_from(&max).is_err());
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`ConversionError`](MathError::ConversionError)
    ///   if the value does not fit into an [`i64`]
    fn try_from(value: &Z) -> Result<Self, Self::Error> {
        // fmpz_get_si returns the i64::MAX or respectively i64::MIN
        // if the value is too large/small to fit into an [`i64`].
        // Hence we are required to manually check if the value is actually correct
        let value_i64 = unsafe { fmpz_get_si(&value.value) };
        if &value_i64 == value {
            Ok(value_i64)
        } else {
            Err(MathError::ConversionError(format!(
                "The provided value has to fit into an i64 and it doesn't as the 
                provided value is {value}."
            )))
        }
    }
}

impl TryFrom<Z> for i64 {
    type Error = MathError;

    /// Converts a [`Z`] into an [`i64`]. If the value is either too large
    /// or too small an error is returned.
    ///
    /// Parameters:
    /// - `value`: the value that will be converted into an [`i64`]
    ///
    /// Returns the value as an [`i64`] or an error if it does not fit
    /// into an [`i64`]
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer::Z;
    ///
    /// let max = Z::from(i64::MAX);
    /// assert_eq!(i64::MAX, i64::try_from(max).unwrap());
    ///
    /// let max = Z::from(u64::MAX) + 1;
    /// assert!(i64::try_from(max).is_err());
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`ConversionError`](MathError::ConversionError)
    ///   if the value does not fit into an [`i64`]
    fn try_from(value: Z) -> Result<Self, Self::Error> {
        i64::try_from(&value)
    }
}

impl TryFrom<&Z> for u64 {
    type Error = MathError;

    /// Converts a [`Z`] into an [`u64`]. If the value is either too large
    /// or too small an error is returned.
    ///
    /// Parameters:
    /// - `value`: the value that will be converted into an [`u64`]
    ///
    /// Returns the value as an [`u64`] or an error if it does not fit
    /// into an [`u64`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer::Z;
    ///
    /// let max = Z::from(u64::MAX);
    /// assert_eq!(u64::MAX, u64::try_from(&max).unwrap());
    ///
    /// let max = Z::from(u64::MAX) + 1;
    /// assert!(u64::try_from(&max).is_err());
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`ConversionError`](MathError::ConversionError)
    ///   if the value does not fit into an [`u64`]
    fn try_from(value: &Z) -> Result<Self, Self::Error> {
        // The result is undefined if value.value does not fit into an ulong or is negative.
        // Hence we are required to manually check if the value is actually correct
        let value_u64 = unsafe { fmpz_get_ui(&value.value) };
        if &value_u64 == value {
            Ok(value_u64)
        } else {
            Err(MathError::ConversionError(format!(
                "The provided value has to fit into an i64 and it doesn't as the 
                provided value is {value}."
            )))
        }
    }
}

impl TryFrom<Z> for u64 {
    type Error = MathError;

    /// Converts a [`Z`] into an [`u64`]. If the value is either too large
    /// or too small an error is returned.
    ///
    /// Parameters:
    /// - `value`: the value that will be converted into an [`u64`]
    ///
    /// Returns the value as an [`u64`] or an error if it does not fit
    /// into an [`u64`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer::Z;
    ///
    /// let max = Z::from(u64::MAX);
    /// assert_eq!(u64::MAX, u64::try_from(max).unwrap());
    ///
    /// let max = Z::from(u64::MAX) + 1;
    /// assert!(u64::try_from(max).is_err());
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`ConversionError`](MathError::ConversionError)
    ///   if the value does not fit into an [`u64`]
    fn try_from(value: Z) -> Result<Self, Self::Error> {
        u64::try_from(&value)
    }
}

impl From<&Vec<u8>> for Z {
    /// Converts a byte vector of type [`u8`] to [`Z`] using [`Z::from_bytes`].
    fn from(value: &Vec<u8>) -> Self {
        Z::from_bytes(value)
    }
}

impl From<Vec<u8>> for Z {
    /// Converts a byte vector of type [`u8`] to [`Z`] using [`Z::from_bytes`].
    fn from(value: Vec<u8>) -> Self {
        Z::from_bytes(&value)
    }
}

#[cfg(test)]
mod test_from_bits {
    use super::Z;

    /// Checks whether small values are correctly instantiated by `from_bits`
    /// and different byte representations are valid
    #[test]
    fn small_values() {
        let vec_0 = vec![false];
        let vec_1 = vec![false, false, false, true];
        let vec_2 = vec![true, true, true, true, true];

        let res_0 = Z::from_bits(&vec_0);
        let res_1 = Z::from_bits(&vec_1);
        let res_2 = Z::from_bits(&vec_2);

        assert_eq!(Z::ZERO, res_0);
        assert_eq!(Z::from(8), res_1);
        assert_eq!(Z::from(31), res_2);
    }

    /// Checks whether large values are correctly instantiated by `from_bits`
    /// and different byte representations are valid
    #[test]
    fn large_values() {
        let vec = vec![true; 64];

        let res = Z::from_bits(&vec);

        assert_eq!(Z::from(u64::MAX), res);
    }
}

#[cfg(test)]
mod test_from_bytes {
    use super::Z;

    /// Checks whether small values are correctly instantiated by `from_bytes`
    /// and different byte representations are valid
    #[test]
    fn small_values() {
        let vec_0: Vec<u8> = vec![0];
        let vec_1: Vec<u8> = vec![0x00, 0x01];
        let vec_2: Vec<u8> = vec![1, 0];

        let res_0 = Z::from_bytes(&vec_0);
        let res_1 = Z::from_bytes(&vec_1);
        let res_2 = Z::from_bytes(&vec_2);

        assert_eq!(Z::ZERO, res_0);
        assert_eq!(Z::from(256), res_1);
        assert_eq!(Z::ONE, res_2);
    }

    /// Checks whether large values are correctly instantiated by `from_bytes`
    /// and different byte representations are valid
    #[test]
    fn large_values() {
        let vec_0: Vec<u8> = vec![255, 255, 255, 255, 255, 255, 255, 255];
        let vec_1: Vec<u8> = vec![0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];

        let res_0 = Z::from_bytes(&vec_0);
        let res_1 = Z::from_bytes(&vec_1);

        assert_eq!(Z::from(u64::MAX), res_0);
        assert_eq!(Z::from(u64::MAX), res_1);
    }

    /// Checks for availability of `from_bytes` for array-inputs and the `from` trait
    /// for vectors of borrowed and owned types
    #[test]
    fn availability() {
        let arr: [u8; 2] = [0x01, 0x01];
        let vec: Vec<u8> = vec![0x01, 0x01];

        let res_0 = Z::from_bytes(&arr);
        let res_1 = Z::from(&vec);
        let res_2 = Z::from(vec);

        assert_eq!(Z::from(257), res_0);
        assert_eq!(Z::from(257), res_1);
        assert_eq!(Z::from(257), res_2);
    }
}

#[cfg(test)]
/// Test the implementation of [`Z::from_utf8`] briefly.
/// This module omits tests that were already provided for [`Z::from_bytes`].
mod test_from_utf8 {
    use super::Z;

    /// Ensures that a wide range of (special) characters are correctly transformed.
    #[test]
    fn characters() {
        let message = "flag{text#1234567890! a_zA-Z$€?/:;,.<>+*}";

        let value = Z::from_utf8(message);

        // easy trick s.t. we don't have to initialize a huge [`Z`] value
        // while this test should still fail if the value changes
        let value_zq = value % 65537;

        assert_eq!(Z::from(58285), value_zq);
    }

    /// Ensure that the empty string results in a zero value.
    #[test]
    fn empty_string() {
        let message = "";

        let value = Z::from_utf8(message);

        assert_eq!(Z::ZERO, value);
    }
}

#[cfg(test)]
/// Test the different implementations for types that implement [`AsInteger`] and [`IntoZ`]
mod tests_from_int {
    use super::*;
    use crate::integer_mod_q::Modulus;

    /// Ensure that the [`From`] trait is available for singed and unsigned integers
    /// of 8, 16, 32, and 64 bit length and for their owned and borrowed variants.
    /// Tested with their maximum value.
    #[test]
    fn rust_int_max() {
        // signed
        let _ = Z::from(i8::MAX);
        let _ = Z::from(i16::MAX);
        let _ = Z::from(i32::MAX);
        let _ = Z::from(i64::MAX);
        let _ = Z::from(&i8::MAX);
        let _ = Z::from(&i16::MAX);
        let _ = Z::from(&i32::MAX);
        let _ = Z::from(&i64::MAX);

        // unsigned
        let _ = Z::from(u8::MAX);
        let _ = Z::from(u16::MAX);
        let _ = Z::from(u32::MAX);
        let _ = Z::from(u64::MAX);
        let _ = Z::from(&u8::MAX);
        let _ = Z::from(&u16::MAX);
        let _ = Z::from(&u32::MAX);
        let _ = Z::from(&u64::MAX);
    }

    /// Ensure that the [`From`] trait is available for singed and unsigned integers
    /// of 8, 16, 32, and 64 bit length and for their owned and borrowed variants.
    /// Tested with their minimum value.
    #[test]
    fn rust_int_min() {
        // signed
        let _ = Z::from(i8::MIN);
        let _ = Z::from(i16::MIN);
        let _ = Z::from(i32::MIN);
        let _ = Z::from(i64::MIN);
        let _ = Z::from(&i8::MIN);
        let _ = Z::from(&i16::MIN);
        let _ = Z::from(&i32::MIN);
        let _ = Z::from(&i64::MIN);

        // unsigned
        let _ = Z::from(u8::MIN);
        let _ = Z::from(u16::MIN);
        let _ = Z::from(u32::MIN);
        let _ = Z::from(u64::MIN);
        let _ = Z::from(&u8::MIN);
        let _ = Z::from(&u16::MIN);
        let _ = Z::from(&u32::MIN);
        let _ = Z::from(&u64::MIN);
    }

    /// Ensure that the [`From`] trait is available for small and large,
    /// borrowed and owned [`Modulus`] instances.
    #[test]
    fn modulus() {
        let val_1 = Z::from(u64::MAX);
        let mod_1 = Modulus::from(&val_1);
        let val_2 = Z::from(10);
        let mod_2 = Modulus::from(&val_2);

        assert_eq!(val_1, Z::from(&mod_1));
        assert_eq!(val_2, Z::from(&mod_2));

        assert_eq!(val_1, Z::from(mod_1));
        assert_eq!(val_2, Z::from(mod_2));
    }

    /// Ensure that the [`From`] trait is available for small and large,
    /// borrowed and owned [`Z`] instances.
    #[test]
    fn z() {
        let original_large = Z::from(u64::MAX);
        let original_small = Z::ONE;

        assert_eq!(original_large, Z::from(&original_large));
        assert_eq!(original_large, original_large.clone());

        assert_eq!(original_small, Z::from(&original_small));
        assert_eq!(original_small, Z::ONE);
    }

    /// Ensure that the [`From`] trait is available for small and large,
    /// borrowed and owned [`fmpz`] instances.
    #[test]
    fn fmpz() {
        let large_z = Z::from(u64::MAX);
        let small_z = Z::ONE;

        assert_eq!(large_z, Z::from(&large_z.value));
        assert_eq!(large_z, Z::from(large_z.value));

        assert_eq!(small_z, Z::from(&small_z.value));
        assert_eq!(small_z, Z::from(small_z.value));
    }
}

#[cfg(test)]
mod tests_from_str {
    use crate::integer::Z;
    use std::str::FromStr;

    /// Ensure that initialization with large numbers works.
    #[test]
    fn max_int_positive() {
        assert!(Z::from_str(&(i64::MAX).to_string()).is_ok());
    }

    /// Ensure that initialization with large numbers (larger than i64) works.
    #[test]
    fn large_positive() {
        assert!(Z::from_str(&"1".repeat(65)).is_ok());
    }

    /// Ensure that initialization with large negative numbers works.
    #[test]
    fn max_int_negative() {
        assert!(Z::from_str(&(i64::MIN).to_string()).is_ok());
    }

    /// Ensure that initialization with large negative numbers (larger than i64) works.
    #[test]
    fn large_negative() {
        let mut s = "-".to_string();
        s.push_str(&"1".repeat(65));

        assert!(Z::from_str(&s).is_ok());
    }

    /// Ensure that wrong initialization yields an Error.
    #[test]
    fn error_wrong_letters() {
        assert!(Z::from_str("hbrkt35itu3gg").is_err());
    }

    /// Ensure that wrong initialization yields an Error.
    #[test]
    fn error_wrong_order() {
        assert!(Z::from_str("3-2").is_err());
    }

    /// Ensure that wrong initialization yields an Error.
    #[test]
    fn error_rational() {
        assert!(Z::from_str("876/543").is_err());
    }

    /// Ensure that wrong initialization yields an Error.
    #[test]
    fn whitespace_mid() {
        assert!(Z::from_str("876 543").is_err());
    }

    /// Ensure that wrong initialization yields an Error.
    #[test]
    fn whitespace_start() {
        assert!(Z::from_str(" 876543").is_err());
    }

    /// Ensure that wrong initialization yields an Error.
    #[test]
    fn whitespace_end() {
        assert!(Z::from_str("876543 ").is_err());
    }

    /// Ensure that wrong initialization yields an Error.
    #[test]
    fn whitespace_minus() {
        assert!(Z::from_str("- 876543").is_err());
    }
}

#[cfg(test)]
mod test_from_str_b {
    use crate::integer::Z;

    /// ensure that an error is returned, if an invalid base is provided
    #[test]
    fn out_of_bounds() {
        let value = "100010";

        assert!(Z::from_str_b(value, -1).is_err());
        assert!(Z::from_str_b(value, 0).is_err());
        assert!(Z::from_str_b(value, 1).is_err());
        assert!(Z::from_str_b(value, 63).is_err());
    }

    /// ensure that from_str works with a binary-string
    #[test]
    fn from_str_binary() {
        assert_eq!(Z::from(20), Z::from_str_b("10100", 2).unwrap());
        assert_eq!(Z::from(-20), Z::from_str_b("-10100", 2).unwrap());
    }

    /// ensure that from_str works with a hex-string
    #[test]
    fn from_str_hex() {
        assert_eq!(Z::from(160), Z::from_str_b("a0", 16).unwrap());
        assert_eq!(Z::from(-170), Z::from_str_b("-aa", 16).unwrap());
    }
}

#[cfg(test)]
mod test_from_fmpz {
    use super::Z;
    use flint_sys::fmpz::{fmpz, fmpz_set_ui};

    /// Ensure that `from_fmpz` is available for small and large numbers
    #[test]
    fn small_numbers() {
        let fmpz_1 = fmpz(0);
        let fmpz_2 = fmpz(100);

        assert_eq!(unsafe { Z::from_fmpz(fmpz_1) }, Z::ZERO);
        assert_eq!(unsafe { Z::from_fmpz(fmpz_2) }, Z::from(100));
    }

    /// Ensure that `from_fmpz` is available for small and large numbers
    #[test]
    fn large_numbers() {
        let mut fmpz_1 = fmpz(0);
        unsafe { fmpz_set_ui(&mut fmpz_1, u64::MAX) }

        assert_eq!(unsafe { Z::from_fmpz(fmpz_1) }, Z::from(u64::MAX));
    }
}

#[cfg(test)]
mod test_from_fmpz_ref {
    use super::Z;

    /// Ensure that `from_fmpz` is available for small and large numbers
    #[test]
    fn large_small_numbers() {
        let mod_1 = Z::from(u64::MAX);
        let mod_2 = Z::ZERO;

        let _ = Z::from_fmpz_ref(&mod_1.value);
        let _ = Z::from_fmpz_ref(&mod_2.value);
    }
}

#[cfg(test)]
mod test_try_from_into_i64 {
    use crate::integer::Z;

    /// ensure that an error is returned, if the value of the [`Z`]
    /// does not fit into an [`i64`]
    #[test]
    fn overflow() {
        assert!(i64::try_from(&Z::from(u64::MAX)).is_err());
        assert!(i64::try_from(&(-1 * Z::from(u64::MAX))).is_err());
        assert!(i64::try_from(Z::from(u64::MAX)).is_err());
        assert!(i64::try_from(-1 * Z::from(u64::MAX)).is_err());
    }

    /// ensure that a correct value is returned for values in bounds.
    #[test]
    fn correct() {
        let min = Z::from(i64::MIN);
        let max = Z::from(i64::MAX);
        let z_42 = Z::from(42);

        assert_eq!(i64::MIN, i64::try_from(&min).unwrap());
        assert_eq!(i64::MAX, i64::try_from(&max).unwrap());
        assert_eq!(0, i64::try_from(&Z::ZERO).unwrap());
        assert_eq!(42, i64::try_from(&z_42).unwrap());

        assert_eq!(i64::MIN, i64::try_from(min).unwrap());
        assert_eq!(i64::MAX, i64::try_from(max).unwrap());
        assert_eq!(0, i64::try_from(Z::ZERO).unwrap());
        assert_eq!(42, i64::try_from(z_42).unwrap());
    }
}

#[cfg(test)]
mod test_try_from_into_u64 {
    use crate::integer::Z;

    /// ensure that an error is returned, if the value of the [`Z`]
    /// does not fit into an [`u64`]
    #[test]
    fn overflow() {
        assert!(u64::try_from(&(Z::from(u64::MAX) + 1)).is_err());
        assert!(u64::try_from(&Z::MINUS_ONE).is_err());
    }

    /// ensure that a correct value is returned for values in bounds.
    #[test]
    fn correct() {
        let min = Z::from(0);
        let max = Z::from(u64::MAX);
        let z_42 = Z::from(42);

        assert_eq!(0, u64::try_from(&min).unwrap());
        assert_eq!(u64::MAX, u64::try_from(&max).unwrap());
        assert_eq!(0, i64::try_from(&Z::ZERO).unwrap());
        assert_eq!(42, i64::try_from(&z_42).unwrap());

        assert_eq!(0, u64::try_from(min).unwrap());
        assert_eq!(u64::MAX, u64::try_from(max).unwrap());
        assert_eq!(0, u64::try_from(Z::ZERO).unwrap());
        assert_eq!(42, u64::try_from(z_42).unwrap());
    }
}