crabka_protocol/codec.rs
1use bytes::{Buf, BufMut};
2
3use crate::ProtocolError;
4
5/// Encode a Kafka wire-protocol value into a buffer at the given protocol version.
6///
7/// `version` is the message-level version negotiated via `ApiVersionsRequest`.
8/// Implementations must produce bytes that are byte-equal to the upstream JVM
9/// `kafka-clients` implementation for the same `(message_type, version, value)`.
10pub trait Encode {
11 fn encode<B: BufMut>(&self, buf: &mut B, version: i16) -> Result<(), ProtocolError>;
12
13 /// Size in bytes that `encode` will write. Must equal the actual count.
14 fn encoded_len(&self, version: i16) -> usize;
15}
16
17/// Decode a Kafka wire-protocol value from a buffer at the given protocol version.
18///
19/// The `'de` lifetime is the lifetime the decoded value may borrow from the input.
20/// Owned-flavor types implement `Decode<'de>` for any `'de` (their output is `'static`).
21/// Borrowed-flavor types implement `Decode<'de>` where `Self: 'de`.
22pub trait Decode<'de>: Sized {
23 fn decode<B: Buf>(buf: &mut B, version: i16) -> Result<Self, ProtocolError>;
24}
25
26/// Like `Decode`, but for borrowed (zero-copy) flavors. Requires a contiguous
27/// buffer because borrowed values reference slices of it.
28pub trait DecodeBorrow<'de>: Sized + 'de {
29 fn decode_borrow(buf: &mut &'de [u8], version: i16) -> Result<Self, ProtocolError>;
30}
31
32/// Implemented by every generated Request struct in `crabka-protocol`.
33///
34/// The `crabka-protocol-codegen` crate emits this impl for every Request type.
35/// Provides the dispatch information (api key, version range, response type)
36/// that the client needs.
37pub trait ProtocolRequest: Encode {
38 /// Kafka API key for this request.
39 const API_KEY: i16;
40 /// Minimum protocol version this Rust type supports.
41 const MIN_VERSION: i16;
42 /// Maximum protocol version this Rust type supports.
43 const MAX_VERSION: i16;
44 /// First version that uses flexible (KIP-482) framing.
45 /// `i16::MAX` for never-flexible messages.
46 const FLEXIBLE_MIN: i16;
47
48 /// Matching response type from `crabka-protocol`.
49 type Response: for<'de> Decode<'de>;
50}