use super::Modulus;
use crate::macros::for_others::implement_for_owned;
use core::fmt;
use flint_sys::fmpz::fmpz_get_str;
use std::{ffi::CStr, ptr::null_mut};
impl From<&Modulus> for String {
fn from(value: &Modulus) -> Self {
value.to_string()
}
}
implement_for_owned!(Modulus, String, From);
impl fmt::Display for Modulus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let c_str_ptr = unsafe { fmpz_get_str(null_mut(), 10, &self.modulus.n[0]) };
let msg = "We expect the pointer to point to a real value and the c_string
not to be null. This error occurs if the provided string does not have UTF-8 format.";
let return_str = unsafe { CStr::from_ptr(c_str_ptr).to_str().expect(msg).to_owned() };
unsafe { libc::free(c_str_ptr as *mut libc::c_void) };
write!(f, "{return_str}")
}
}
#[cfg(test)]
mod test_to_string {
use crate::integer_mod_q::Modulus;
use std::str::FromStr;
#[test]
fn working_large() {
let cmp_str = "1".repeat(65);
let cmp = Modulus::from_str(&cmp_str).unwrap();
assert_eq!(cmp_str, cmp.to_string());
}
#[test]
fn working_positive() {
let cmp_str = "42";
let cmp = Modulus::from_str(cmp_str).unwrap();
assert_eq!(cmp_str, cmp.to_string());
}
#[test]
fn working_use_result_of_to_string_as_input() {
let cmp_str = "42";
let cmp = Modulus::from_str(cmp_str).unwrap();
let cmp_str_2 = cmp.to_string();
assert!(Modulus::from_str(&cmp_str_2).is_ok());
}
#[test]
fn into_works_properly() {
let cmp = "6";
let modulus = Modulus::from_str(cmp).unwrap();
let string: String = modulus.clone().into();
let borrowed_string: String = (&modulus).into();
assert_eq!(cmp, string);
assert_eq!(cmp, borrowed_string);
}
}