Skip to main content

netgauze_parse_utils/
error.rs

1// Copyright (C) 2026-present The NetGauze Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//    http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12// implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use serde::{Deserialize, Serialize};
17
18/// Infrastructure-level parsing error.
19/// Represents only *structural* failures — buffer exhausted or value out of
20/// range. Domain-specific validation lives in per-PDU error enums.
21#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
22pub enum ParseError {
23    #[error(
24        "unexpected end of buffer at byte offset {offset} (needed {needed}, available {available})"
25    )]
26    UnexpectedEof {
27        offset: usize,
28        needed: usize,
29        available: usize,
30    },
31
32    #[error(
33        "padded read exceeds capacity at byte offset {offset} (requested {requested}, capacity {ret_len})"
34    )]
35    InvalidPaddingLength {
36        offset: usize,
37        requested: usize,
38        ret_len: usize,
39    },
40}
41
42impl ParseError {
43    #[cold]
44    #[inline(never)]
45    pub fn eof(offset: usize, needed: usize, available: usize) -> Self {
46        Self::UnexpectedEof {
47            offset,
48            needed,
49            available,
50        }
51    }
52    #[cold]
53    #[inline(never)]
54    pub fn invalid_padding_length(offset: usize, requested: usize, ret_len: usize) -> Self {
55        Self::InvalidPaddingLength {
56            offset,
57            requested,
58            ret_len,
59        }
60    }
61
62    #[inline]
63    pub fn offset(&self) -> usize {
64        match self {
65            Self::UnexpectedEof { offset, .. } | Self::InvalidPaddingLength { offset, .. } => {
66                *offset
67            }
68        }
69    }
70
71    #[inline]
72    pub fn is_incomplete(&self) -> bool {
73        matches!(self, Self::UnexpectedEof { .. })
74    }
75}