ifc_lite_geometry_runtime/
protocol_response.rs1use super::{MAX_RESPONSE_BYTES, VERSION};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum ProtocolError {
8 PayloadSize,
9 Version,
10 RequestId,
11 InvalidUtf8,
12 MeshChunkSize,
13 ResultSize,
14}
15impl ProtocolError {
16 pub fn as_str(self) -> &'static str {
17 match self {
18 Self::PayloadSize => "invalid kernel payload size",
19 Self::Version => "unsupported kernel protocol version",
20 Self::RequestId => "kernel response request ID mismatch",
21 Self::InvalidUtf8 => "invalid UTF-8 in kernel error",
22 Self::MeshChunkSize => "mesh transfer exceeds scalar chunk limit",
23 Self::ResultSize => "unexpected kernel result size",
24 }
25 }
26}
27impl std::fmt::Display for ProtocolError {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 f.write_str(self.as_str())
30 }
31}
32impl std::error::Error for ProtocolError {}
33
34#[derive(Debug, PartialEq, Eq)]
36pub enum KernelResponse<'a> {
37 Success(&'a [u8]),
38 Failure { status: i32, message: &'a str },
39}
40
41pub fn decode_response(request_id: u32, bytes: &[u8]) -> Result<KernelResponse<'_>, ProtocolError> {
43 if !(12..=MAX_RESPONSE_BYTES).contains(&bytes.len()) {
44 return Err(ProtocolError::PayloadSize);
45 }
46 if bytes[..4] != VERSION.to_le_bytes() {
47 return Err(ProtocolError::Version);
48 }
49 if bytes[4..8] != request_id.to_le_bytes() {
50 return Err(ProtocolError::RequestId);
51 }
52 let status = i32::from_le_bytes(bytes[8..12].try_into().expect("four bytes"));
53 if status == 0 {
54 return Ok(KernelResponse::Success(&bytes[12..]));
55 }
56 let message = std::str::from_utf8(&bytes[12..]).map_err(|_| ProtocolError::InvalidUtf8)?;
57 Ok(KernelResponse::Failure { status, message })
58}