Skip to content

Commit

Permalink
feat: impl ToSchema for Ipv4Addr, Ipv6Addr, IpAddr (#1014)
Browse files Browse the repository at this point in the history
- I noticed that ToSchema was missing for these types from std::net
- This was needed for the Shuttlings Christmas Code Hunt 2024 (challenge 2)
  • Loading branch information
Samyak2 authored Dec 29, 2024
1 parent 994d853 commit 0478860
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
13 changes: 12 additions & 1 deletion crates/oapi-macros/src/schema_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,8 @@ fn is_primitive(name: &str) -> bool {
| "i128"
| "f32"
| "f64"
| "Ipv4Addr"
| "Ipv6Addr"
)
}

Expand Down Expand Up @@ -260,6 +262,9 @@ impl TryToTokens for SchemaType<'_> {
"PrimitiveDateTime" | "OffsetDateTime" => {
schema_type_tokens(tokens, oapi, SchemaTypeInner::String, self.nullable)
}
"Ipv4Addr" | "Ipv6Addr" | "IpAddr" => {
schema_type_tokens(tokens, oapi, SchemaTypeInner::String, self.nullable)
}
_ => schema_type_tokens(tokens, oapi, SchemaTypeInner::Object, self.nullable),
};
Ok(())
Expand Down Expand Up @@ -385,7 +390,7 @@ impl Type<'_> {
fn is_known_format(name: &str) -> bool {
matches!(
name,
"i8" | "i16" | "i32" | "u8" | "u16" | "u32" | "i64" | "u64" | "f32" | "f64"
"i8" | "i16" | "i32" | "u8" | "u16" | "u32" | "i64" | "u64" | "f32" | "f64" | "Ipv4Addr" | "Ipv6Addr"
)
}

Expand Down Expand Up @@ -456,6 +461,12 @@ impl TryToTokens for Type<'_> {
#[cfg(feature = "time")]
"PrimitiveDateTime" | "OffsetDateTime" => {
tokens.extend(quote! { #oapi::oapi::SchemaFormat::KnownFormat(#oapi::oapi::KnownFormat::DateTime) })
},
"Ipv4Addr" => {
tokens.extend(quote! { #oapi::oapi::SchemaFormat::KnownFormat(#oapi::oapi::KnownFormat::Ipv4) })
},
"Ipv6Addr" => {
tokens.extend(quote! { #oapi::oapi::SchemaFormat::KnownFormat(#oapi::oapi::KnownFormat::Ipv6) })
}
_ => (),
};
Expand Down
13 changes: 13 additions & 0 deletions crates/oapi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,19 @@ impl_to_schema_primitive!(
);
impl_to_schema!(&str);

impl_to_schema!(std::net::Ipv4Addr);
impl_to_schema!(std::net::Ipv6Addr);

impl ToSchema for std::net::IpAddr {
fn to_schema(components: &mut Components) -> RefOr<schema::Schema> {
crate::RefOr::Type(Schema::OneOf(
OneOf::default()
.item(std::net::Ipv4Addr::to_schema(components))
.item(std::net::Ipv6Addr::to_schema(components)),
))
}
}

#[cfg(feature = "chrono")]
impl_to_schema_primitive!(chrono::NaiveDate, chrono::Duration, chrono::NaiveDateTime);
#[cfg(feature = "chrono")]
Expand Down

0 comments on commit 0478860

Please sign in to comment.