Skip to content

Commit

Permalink
fix: deserialize duration and memory size error
Browse files Browse the repository at this point in the history
  • Loading branch information
Serein207 committed May 15, 2024
1 parent 88714b4 commit ee71812
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 22 deletions.
20 changes: 10 additions & 10 deletions src/model/types/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,17 @@ impl<'de> Visitor<'de> for DurationVisitor {
where
E: de::Error,
{
if let Some((value, unit)) = value.split_once(|c: char| c.is_ascii_alphabetic()) {
let value = value.parse().expect("Invalid duration");
let unit = DurationUnit::from_str(unit).unwrap_or(DurationUnit::Milliseconds);
let (value, unit) = value.split_at(
value
.find(|c: char| c.is_ascii_alphabetic())
.unwrap_or(value.len()),
);
let value = value.parse().map_err(|_| {
de::Error::invalid_value(de::Unexpected::Str(value), &"a valid integer")
})?;
let unit = DurationUnit::from_str(unit).unwrap_or(DurationUnit::Milliseconds);

Ok(Duration { value, unit })
} else {
Err(de::Error::invalid_value(
serde::de::Unexpected::Str(value),
&self,
))
}
Ok(Duration { value, unit })
}
}

Expand Down
23 changes: 11 additions & 12 deletions src/model/types/memory_size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,17 @@ impl<'de> Deserialize<'de> for MemorySize {
where
E: de::Error,
{
if let Some((value, unit)) = value.split_once(|c: char| c.is_ascii_alphabetic()) {
let value = value.parse().expect("Invalid memory size");
Ok(MemorySize {
value,
unit: MemorySizeUnit::from_str(unit).unwrap_or(MemorySizeUnit::MiB),
})
} else {
Ok(MemorySize {
value: value.parse::<u32>().unwrap_or(128),
unit: MemorySizeUnit::MiB,
})
}
let (value, unit) = value.split_at(
value
.find(|c: char| c.is_ascii_alphabetic())
.unwrap_or(value.len()),
);
let value = value.parse().map_err(|_| {
de::Error::invalid_value(de::Unexpected::Str(value), &"a valid integer")
})?;
let unit = MemorySizeUnit::from_str(unit).unwrap_or(MemorySizeUnit::MiB);

Ok(MemorySize { value, unit })
}
}

Expand Down

1 comment on commit ee71812

@Jisu-Woniu
Copy link
Member

@Jisu-Woniu Jisu-Woniu commented on ee71812 Aug 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

把这段代码移到 impl FromStr for Duration / MemorySize 里面会更好

Please sign in to comment.