feat: add optional i64 for response field
This commit is contained in:
@@ -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)]
|
#[derive(Serialize)]
|
||||||
pub struct SimpleResponse {
|
pub struct SimpleResponse {
|
||||||
pub code: i64,
|
pub code: i64,
|
||||||
pub message: String,
|
pub message: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct OptionalI64(pub Option<i64>);
|
||||||
|
|
||||||
|
impl OptionalI64 {
|
||||||
|
// 构造函数:从 i64 创建 Some
|
||||||
|
pub fn new(value: i64) -> Self {
|
||||||
|
OptionalI64(Some(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构造函数:直接创建 None
|
||||||
|
pub fn none() -> Self {
|
||||||
|
OptionalI64(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从 Option<i64> 转换
|
||||||
|
pub fn from_option(value: Option<i64>) -> Self {
|
||||||
|
OptionalI64(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<i64> for OptionalI64 {
|
||||||
|
fn from(value: i64) -> Self {
|
||||||
|
OptionalI64(Some(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl From<Option<i64>> for OptionalI64 {
|
||||||
|
fn from(value: Option<i64>) -> Self {
|
||||||
|
OptionalI64(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromStr for OptionalI64 {
|
||||||
|
type Err = std::num::ParseIntError;
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
if s.is_empty() || s.eq_ignore_ascii_case("null") {
|
||||||
|
Ok(OptionalI64(None))
|
||||||
|
} else {
|
||||||
|
s.parse::<i64>().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<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
T: Display,
|
||||||
|
S: Serializer,
|
||||||
|
{
|
||||||
|
serializer.collect_str(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
|
||||||
|
where
|
||||||
|
T: FromStr,
|
||||||
|
T::Err: Display,
|
||||||
|
D: Deserializer<'de>,
|
||||||
|
{
|
||||||
|
String::deserialize(deserializer)?
|
||||||
|
.parse()
|
||||||
|
.map_err(de::Error::custom)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user