Skip to content

Commit

Permalink
Use encode/decode helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
rukai committed Aug 27, 2024
1 parent 9f4be17 commit 0bb989b
Show file tree
Hide file tree
Showing 2 changed files with 459 additions and 1,110 deletions.
33 changes: 29 additions & 4 deletions protocol_codegen/src/generate_messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ pub fn run() -> Result<(), Error> {
let variant = request_type.trim_end_matches("Request");
writeln!(
module_file,
"RequestKind::{variant}(x) => x.encode(bytes, version).with_context(|| format!(\"Failed to encode {request_type} v{{version}} body\")),"
"RequestKind::{variant}(x) => encode(x, bytes, version),"
)?;
}
writeln!(module_file, "}}")?;
Expand All @@ -302,7 +302,7 @@ pub fn run() -> Result<(), Error> {
let variant = request_type.trim_end_matches("Request");
writeln!(
module_file,
"ApiKey::{variant}Key => {request_type}::decode(bytes, version).with_context(|| format!(\"Failed to decode {request_type} v{{version}} body\")).map(RequestKind::{variant}),"
"ApiKey::{variant}Key => Ok(RequestKind::{variant}(decode(bytes, version)?)),"
)?;
}
writeln!(module_file, "}}")?;
Expand All @@ -323,6 +323,31 @@ pub fn run() -> Result<(), Error> {
writeln!(module_file)?;
}

writeln!(
module_file,
r#"
fn decode<T: Decodable>(bytes: &mut bytes::Bytes, version: i16) -> Result<T> {{
T::decode(bytes, version).with_context(|| {{
format!(
"Failed to decode {{}} v{{}} body",
std::any::type_name::<T>(),
version
)
}})
}}
fn encode<T: Encodable>(encodable: &T, bytes: &mut bytes::BytesMut, version: i16) -> Result<()> {{
encodable.encode(bytes, version).with_context(|| {{
format!(
"Failed to encode {{}} v{{}} body",
std::any::type_name::<T>(),
version
)
}})
}}
"#
)?;

writeln!(
module_file,
"/// Wrapping enum for all responses in the Kafka protocol."
Expand Down Expand Up @@ -353,7 +378,7 @@ pub fn run() -> Result<(), Error> {
let variant = response_type.trim_end_matches("Response");
writeln!(
module_file,
"ResponseKind::{variant}(x) => x.encode(bytes, version).with_context(|| format!(\"Failed to encode {response_type} v{{version}} body\")),"
"ResponseKind::{variant}(x) => encode(x, bytes, version),"
)?;
}
writeln!(module_file, "}}")?;
Expand All @@ -372,7 +397,7 @@ pub fn run() -> Result<(), Error> {
let variant = response_type.trim_end_matches("Response");
writeln!(
module_file,
"ApiKey::{variant}Key => {response_type}::decode(bytes, version).with_context(|| format!(\"Failed to decode {response_type} v{{version}} body\")).map(ResponseKind::{variant}),"
"ApiKey::{variant}Key => Ok(ResponseKind::{variant}(decode(bytes, version)?)),"
)?;
}
writeln!(module_file, "}}")?;
Expand Down
Loading

0 comments on commit 0bb989b

Please sign in to comment.