malachite_nz/integer/conversion/
serde.rs1use crate::integer::{Integer, SerdeInteger};
10use crate::natural::Natural;
11use alloc::string::String;
12use core::convert::TryFrom;
13use malachite_base::num::conversion::traits::FromStringBase;
14
15impl From<Integer> for SerdeInteger {
16 #[inline]
17 fn from(x: Integer) -> Self {
18 Self(format!("{x:#x}"))
19 }
20}
21
22impl TryFrom<SerdeInteger> for Integer {
23 type Error = String;
24
25 #[inline]
26 fn try_from(s: SerdeInteger) -> Result<Self, String> {
27 if s.0.starts_with('-') {
28 if s.0.starts_with("-0x") {
29 Ok(Self::from_sign_and_abs(
30 false,
31 Natural::from_string_base(16, &s.0[3..])
32 .ok_or_else(|| format!("Unrecognized digits in {}", s.0))?,
33 ))
34 } else {
35 Err(format!(
36 "String '{}' starts with '-' but not with '-0x'",
37 s.0
38 ))
39 }
40 } else if s.0.starts_with("0x") {
41 Ok(Self::from(
42 Natural::from_string_base(16, &s.0[2..])
43 .ok_or_else(|| format!("Unrecognized digits in {}", s.0))?,
44 ))
45 } else {
46 Err(format!(
47 "String '{}' does not start with '0x' or '-0x'",
48 s.0
49 ))
50 }
51 }
52}