malachite_float/float/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::float::SerdeFloat;
10use crate::{ComparableFloatRef, Float};
11use alloc::format;
12use alloc::string::String;
13use malachite_base::num::conversion::traits::FromStringBase;
14
15impl From<Float> for SerdeFloat {
16 #[inline]
17 fn from(x: Float) -> Self {
18 // `ComparableFloat`'s `Display` rather than `Float`'s, because it writes the precision
19 // after a `#`; the digits alone do not determine one, so `Float`'s own output would not
20 // round-trip.
21 Self(format!("{:#x}", ComparableFloatRef(&x)))
22 }
23}
24
25impl TryFrom<SerdeFloat> for Float {
26 type Error = String;
27
28 #[inline]
29 fn try_from(s: SerdeFloat) -> Result<Self, String> {
30 Self::from_string_base(16, &s.0).ok_or_else(|| format!("Unrecognized digits in {}", s.0))
31 }
32}