Skip to content

Commit

Permalink
Merge pull request #33 from k9withabone/limit-string-conversion
Browse files Browse the repository at this point in the history
feat(service): add `Limit` string conversions
  • Loading branch information
k9withabone authored Oct 13, 2024
2 parents 6ea9c4e + 65ae95e commit de3af7f
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 5 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ sort_commits = "oldest"

[package]
name = "compose_spec"
version = "0.3.0-alpha.2"
version = "0.3.0-alpha.3"
authors.workspace = true
edition.workspace = true
license.workspace = true
Expand Down
36 changes: 33 additions & 3 deletions src/service/limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
//! [`Service`](super::Service).

use std::{
fmt::{self, Formatter},
fmt::{self, Display, Formatter},
marker::PhantomData,
str::FromStr,
};

use serde::{
Expand Down Expand Up @@ -44,6 +45,27 @@ impl From<ByteValue> for Limit<ByteValue> {
}
}

impl<T: Display> Display for Limit<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Value(value) => value.fmt(f),
Self::Unlimited => f.write_str("-1"),
}
}
}

impl<T: FromStr> FromStr for Limit<T> {
type Err = T::Err;

fn from_str(s: &str) -> Result<Self, Self::Err> {
if s == "-1" {
Ok(Self::Unlimited)
} else {
s.parse().map(Self::Value)
}
}
}

impl<T: Serialize> Serialize for Limit<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Expand Down Expand Up @@ -88,10 +110,18 @@ impl<'de, T: Deserialize<'de>> de::Visitor<'de> for Visitor<T> {
}

fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
T::deserialize(v.into_deserializer()).map(Limit::Value)
if v == "-1" {
Ok(Limit::Unlimited)
} else {
T::deserialize(v.into_deserializer()).map(Limit::Value)
}
}

fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
T::deserialize(v.into_deserializer()).map(Limit::Value)
if v == "-1" {
Ok(Limit::Unlimited)
} else {
T::deserialize(v.into_deserializer()).map(Limit::Value)
}
}
}

0 comments on commit de3af7f

Please sign in to comment.