Skip to main content

fixed_record/
error.rs

1use std::{fmt, io};
2
3/// Errors that can occur while parsing or operating on fixed-width records.
4/// 固定長データのパース処理や操作中に発生するエラーを表します。
5#[derive(Debug)]
6pub enum Error {
7    /// The input is shorter than the expected fixed width.
8    /// 入力データの長さが、期待される固定長サイズよりも短い場合です。
9    ///
10    /// This can happen when a 10-byte field receives only 5 bytes of data.
11    /// 例えば、10バイト必要なフィールドに対して、5バイトのデータしか与えられなかった場合などに発生します。
12    TooShort,
13
14    /// UTF-8 conversion failed for a byte field.
15    /// バイト列から文字列(UTF-8)への変換に失敗した場合です。
16    ///
17    /// This occurs when a fixed-width field contains invalid UTF-8 bytes.
18    /// 固定長フィールド内に、UTF-8 として不正なバイトシーケンスが含まれている場合に発生します。
19    ///
20    /// For encodings such as Shift_JIS, read the field as bytes and decode it separately.
21    /// Shift_JIS など他のエンコーディングを扱う場合は、バイト列として取得し別途デコードしてください。
22    Utf8Error,
23    /// The input ended in the middle of a fixed-width record.
24    /// 固定長レコードの途中で入力が終わった場合です。
25    IncompleteRecord {
26        expected: usize,
27        actual: usize,
28    },
29    /// An I/O error occurred while using `Reader`, `Writer`, or related operations.
30    /// `Reader` / `Writer` などの I/O 処理中に発生したエラーです。
31    Io(io::Error),
32    /// A `Reader` found bytes that did not match the configured record separator.
33    /// `Reader` が設定されたレコード区切りと一致しないバイト列を検出した場合です。
34    UnexpectedSeparator {
35        expected: &'static [u8],
36        actual: Vec<u8>,
37    },
38    /// A field value exceeded the fixed width of the target field.
39    /// フィールドに入れる値が固定長幅を超えた場合です。
40    FieldOverflow {
41        field: &'static str,
42        size: usize,
43        actual: usize,
44    },
45    /// A range search specified a start value greater than its end value.
46    /// 範囲検索で開始値が終了値より大きく指定された場合です。
47    InvalidRange {
48        field: &'static str,
49        start: Vec<u8>,
50        end: Vec<u8>,
51    },
52    /// A `Reader` sequence check found a descending key or a forbidden duplicate key.
53    /// `Reader` のシーケンスチェックで、現在レコードが前回レコードより小さい、または同一禁止設定で同一だった場合です。
54    SequenceError {
55        fields: Vec<&'static str>,
56        previous: Vec<Vec<u8>>,
57        current: Vec<Vec<u8>>,
58    },
59    AlignmentError,
60    ParseError,
61}
62
63impl fmt::Display for Error {
64    /// Formats the error as a short user-facing message.
65    /// エラー内容を利用者向けの短いメッセージとして整形します。
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Error::TooShort => write!(f, "input data is too short for the fixed length"),
69            Error::Utf8Error => write!(f, "input data contains invalid UTF-8 sequence"),
70            Error::IncompleteRecord { expected, actual } => write!(
71                f,
72                "incomplete fixed record: expected {expected} bytes, got {actual} bytes"
73            ),
74            Error::Io(err) => write!(f, "I/O error while processing fixed record: {err}"),
75            Error::UnexpectedSeparator { expected, actual } => write!(
76                f,
77                "unexpected record separator: expected {expected:?}, got {actual:?}"
78            ),
79            Error::FieldOverflow {
80                field,
81                size,
82                actual,
83            } => write!(
84                f,
85                "field `{field}` is too wide for the fixed length: expected at most {size} bytes, got {actual} bytes"
86            ),
87            Error::InvalidRange { field, start, end } => write!(
88                f,
89                "invalid range for field `{field}`: start {start:?} is greater than end {end:?}"
90            ),
91            Error::SequenceError {
92                fields,
93                previous,
94                current,
95            } => write!(
96                f,
97                "record sequence is not ascending for fields {fields:?}: previous={previous:?}, current={current:?}"
98            ),
99            Error::AlignmentError => write!(f, "Alignment error"),
100            Error::ParseError => write!(f, "failed to parse field value"),
101        }
102    }
103}
104
105impl PartialEq for Error {
106    /// Compares I/O errors by `ErrorKind` and other errors by variant and payload.
107    /// I/O エラーは `ErrorKind` で比較し、それ以外は variant と値で比較します。
108    fn eq(&self, other: &Self) -> bool {
109        match (self, other) {
110            (Error::TooShort, Error::TooShort) => true,
111            (Error::Utf8Error, Error::Utf8Error) => true,
112            (
113                Error::IncompleteRecord {
114                    expected: left_expected,
115                    actual: left_actual,
116                },
117                Error::IncompleteRecord {
118                    expected: right_expected,
119                    actual: right_actual,
120                },
121            ) => left_expected == right_expected && left_actual == right_actual,
122            (Error::Io(left), Error::Io(right)) => left.kind() == right.kind(),
123            (
124                Error::UnexpectedSeparator {
125                    expected: left_expected,
126                    actual: left_actual,
127                },
128                Error::UnexpectedSeparator {
129                    expected: right_expected,
130                    actual: right_actual,
131                },
132            ) => left_expected == right_expected && left_actual == right_actual,
133            (
134                Error::FieldOverflow {
135                    field: left_field,
136                    size: left_size,
137                    actual: left_actual,
138                },
139                Error::FieldOverflow {
140                    field: right_field,
141                    size: right_size,
142                    actual: right_actual,
143                },
144            ) => {
145                left_field == right_field && left_size == right_size && left_actual == right_actual
146            }
147            (
148                Error::InvalidRange {
149                    field: left_field,
150                    start: left_start,
151                    end: left_end,
152                },
153                Error::InvalidRange {
154                    field: right_field,
155                    start: right_start,
156                    end: right_end,
157                },
158            ) => left_field == right_field && left_start == right_start && left_end == right_end,
159            (
160                Error::SequenceError {
161                    fields: left_fields,
162                    previous: left_previous,
163                    current: left_current,
164                },
165                Error::SequenceError {
166                    fields: right_fields,
167                    previous: right_previous,
168                    current: right_current,
169                },
170            ) => {
171                left_fields == right_fields
172                    && left_previous == right_previous
173                    && left_current == right_current
174            }
175            (Error::AlignmentError, Error::AlignmentError) => true,
176            (Error::ParseError, Error::ParseError) => true,
177            _ => false,
178        }
179    }
180}
181
182impl Eq for Error {}
183
184impl std::error::Error for Error {
185    /// Returns the wrapped I/O error as the source when one exists.
186    /// ラップしている I/O エラーがあれば原因として返します。
187    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
188        match self {
189            Error::Io(err) => Some(err),
190            _ => None,
191        }
192    }
193}
194
195impl From<io::Error> for Error {
196    /// Converts a standard I/O error into a fixed-record error.
197    /// 標準 I/O エラーを固定長レコード用エラーへ変換します。
198    fn from(err: io::Error) -> Self {
199        Self::Io(err)
200    }
201}