Skip to main content

kacrab_protocol/record/
header.rs

1//! [`RecordHeader`] — non-nullable key, nullable value, on a single record.
2
3use bytes::{Bytes, BytesMut};
4
5use super::Result;
6
7/// A record header.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct RecordHeader {
10    /// Header key (non-nullable; on-wire length must be `>= 0`).
11    pub key: Bytes,
12    /// Header value. `None` when the on-wire length is `-1`.
13    pub value: Option<Bytes>,
14}
15
16impl RecordHeader {
17    /// Return the exact encoded length of this header.
18    pub fn encoded_len(&self) -> Result<usize> {
19        let len = super::bytes_field_len("header key", &self.key)?;
20        super::add_encoded_len(
21            "header value",
22            len,
23            super::nullable_bytes_field_len("header value", self.value.as_ref())?,
24        )
25    }
26
27    /// Encode this header into `buf`.
28    pub fn encode(&self, buf: &mut BytesMut) -> Result<()> {
29        super::write_bytes_field(buf, "header key", &self.key)?;
30        super::write_nullable_bytes_field(buf, "header value", self.value.as_ref())?;
31        Ok(())
32    }
33
34    /// Decode one header from `buf`. Rejects negative key lengths.
35    pub fn decode(buf: &mut Bytes) -> Result<Self> {
36        let key = super::read_bytes_field(buf, "header key")?;
37        let value = super::read_nullable_bytes_field(buf, "header value")?;
38
39        Ok(Self { key, value })
40    }
41}