diff --git a/src/model/http_body/common.rs b/src/model/http_body/common.rs index 4df7526..5a98c74 100644 --- a/src/model/http_body/common.rs +++ b/src/model/http_body/common.rs @@ -1,7 +1,88 @@ -use serde::{Serialize,Deserialize}; +use serde::{Deserialize, Serialize}; +use std::fmt::{Display, Formatter, Result as FmtResult}; +use std::num::ParseIntError; +use std::str::FromStr; #[derive(Serialize)] pub struct SimpleResponse { pub code: i64, pub message: String, -} \ No newline at end of file +} + +#[derive(Debug)] +pub struct OptionalI64(pub Option); + +impl OptionalI64 { + // 构造函数:从 i64 创建 Some + pub fn new(value: i64) -> Self { + OptionalI64(Some(value)) + } + + // 构造函数:直接创建 None + pub fn none() -> Self { + OptionalI64(None) + } + + // 从 Option 转换 + pub fn from_option(value: Option) -> Self { + OptionalI64(value) + } +} + +impl From for OptionalI64 { + fn from(value: i64) -> Self { + OptionalI64(Some(value)) + } +} +impl From> for OptionalI64 { + fn from(value: Option) -> Self { + OptionalI64(value) + } +} + +impl FromStr for OptionalI64 { + type Err = std::num::ParseIntError; + + fn from_str(s: &str) -> Result { + if s.is_empty() || s.eq_ignore_ascii_case("null") { + Ok(OptionalI64(None)) + } else { + s.parse::().map(|n| OptionalI64(Some(n))) + } + } +} + +impl Display for OptionalI64 { + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + match self.0 { + Some(num) => write!(f, "{}", num), // 有值时输出数字 + None => write!(f, ""), // None 时输出空字符串 + } + } +} + +pub mod number_stringify { + use std::fmt::Display; + use std::str::FromStr; + + use serde::{de, Deserialize, Deserializer, Serializer}; + + pub fn serialize(value: &T, serializer: S) -> Result + where + T: Display, + S: Serializer, + { + serializer.collect_str(value) + } + + pub fn deserialize<'de, T, D>(deserializer: D) -> Result + where + T: FromStr, + T::Err: Display, + D: Deserializer<'de>, + { + String::deserialize(deserializer)? + .parse() + .map_err(de::Error::custom) + } +}