use crate::WireError;
use crate::codec::{WireDecode, WireEncode, read_u32_le};
use bytes::{BufMut, BytesMut};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdentityResponse {
pub user_id: u32,
}
impl WireEncode for IdentityResponse {
fn encoded_size(&self) -> usize {
4
}
fn encode(&self, buf: &mut BytesMut) {
buf.put_u32_le(self.user_id);
}
}
impl WireDecode for IdentityResponse {
fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> {
let user_id = read_u32_le(buf, 0)?;
Ok((Self { user_id }, 4))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip() {
let resp = IdentityResponse { user_id: 42 };
let bytes = resp.to_bytes();
assert_eq!(bytes.len(), 4);
let (decoded, consumed) = IdentityResponse::decode(&bytes).unwrap();
assert_eq!(consumed, 4);
assert_eq!(decoded, resp);
}
#[test]
fn truncated_returns_error() {
let resp = IdentityResponse { user_id: 1 };
let bytes = resp.to_bytes();
for i in 0..bytes.len() {
assert!(
IdentityResponse::decode(&bytes[..i]).is_err(),
"expected error for truncation at byte {i}"
);
}
}
}