use super::Zq;
use crate::macros::for_others::implement_for_owned;
use core::fmt;
use std::string::FromUtf8Error;
impl From<&Zq> for String {
fn from(value: &Zq) -> Self {
value.to_string()
}
}
implement_for_owned!(Zq, String, From);
impl fmt::Display for Zq {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} mod {}", self.value, self.modulus)
}
}
impl Zq {
pub fn to_utf8(&self) -> Result<String, FromUtf8Error> {
String::from_utf8(
self.get_representative_least_nonnegative_residue()
.to_bytes(),
)
}
}
#[cfg(test)]
mod test_to_string {
use crate::integer_mod_q::Zq;
use std::str::FromStr;
#[test]
fn working_large_positive() {
let cmp = Zq::from_str(&format!("{} mod {}", u64::MAX, u128::MAX)).unwrap();
assert_eq!(format!("{} mod {}", u64::MAX, u128::MAX), cmp.to_string());
}
#[test]
fn working_large_negative() {
let cmp = Zq::from_str(&format!("-{} mod {}", u64::MAX, u128::MAX)).unwrap();
let diff = u128::MAX - u64::MAX as u128;
assert_eq!(format!("{diff} mod {}", u128::MAX), cmp.to_string());
}
#[test]
fn working_positive() {
let cmp = Zq::from_str("42 mod 60").unwrap();
assert_eq!("42 mod 60", cmp.to_string());
}
#[test]
fn working_negative() {
let cmp = Zq::from_str("-40 mod 3").unwrap();
assert_eq!("2 mod 3", cmp.to_string());
}
#[test]
fn working_use_result_of_to_string_as_input() {
let cmp = Zq::from((42, 10));
let cmp_str = cmp.to_string();
assert!(Zq::from_str(&cmp_str).is_ok());
}
#[test]
fn into_works_properly() {
let cmp = "6 mod 11";
let zq = Zq::from_str(cmp).unwrap();
let string: String = zq.clone().into();
let borrowed_string: String = (&zq).into();
assert_eq!(cmp, string);
assert_eq!(cmp, borrowed_string);
}
}
#[cfg(test)]
mod test_to_utf8 {
use super::Zq;
#[test]
fn inverse_to_from_utf8() {
let cmp_text = "Test!";
let value = Zq::from_utf8(cmp_text, u64::MAX).unwrap();
let text = value.to_utf8().unwrap();
assert_eq!(cmp_text, text);
}
}