Skip to main content

malachite_nz/integer/conversion/
serde.rs

1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use 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}