cidian/error.rs
1use std::char::DecodeUtf16Error;
2use std::collections::TryReserveError;
3use std::fmt;
4use std::io;
5use std::path::PathBuf;
6use std::str::Utf8Error;
7
8/// A dictionary format understood by `cidian-rs`.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10#[non_exhaustive]
11pub enum Format {
12 /// Baidu mobile category dictionary (`.bcd`).
13 Bcd,
14 /// Baidu desktop category dictionary (`.bdict`).
15 Bdict,
16 /// QQ Pinyin category dictionary (`.qpyd`).
17 Qpyd,
18 /// QQ Pinyin Cell Dictionary (`.qcel`).
19 Qcel,
20 /// Sogou Cell Dictionary (`.scel`).
21 Scel,
22}
23
24impl fmt::Display for Format {
25 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
26 match self {
27 Self::Bcd => formatter.write_str("BCD"),
28 Self::Bdict => formatter.write_str("BDICT"),
29 Self::Qpyd => formatter.write_str("QPYD"),
30 Self::Qcel => formatter.write_str("QCEL"),
31 Self::Scel => formatter.write_str("SCEL"),
32 }
33 }
34}
35
36/// Errors returned while reading or parsing a dictionary.
37///
38/// Every variant retains the source format and structured diagnostic data so
39/// callers can distinguish malformed input, unsupported data, and I/O errors
40/// without inspecting the displayed error message.
41#[derive(Debug, thiserror::Error)]
42#[non_exhaustive]
43pub enum Error {
44 /// A dictionary file could not be read.
45 #[error("failed to read {format} dictionary `{path}`: {source}")]
46 Io {
47 /// Dictionary format requested by the caller.
48 format: Format,
49 /// Path that could not be read.
50 path: PathBuf,
51 /// Underlying filesystem error.
52 #[source]
53 source: io::Error,
54 },
55
56 /// A read extended past the available input.
57 #[error(
58 "unexpected end of {format} data at byte {offset:#x}: needed {needed} bytes, {available} available"
59 )]
60 UnexpectedEof {
61 /// Dictionary format being parsed.
62 format: Format,
63 /// Byte offset at which the read was attempted.
64 offset: usize,
65 /// Number of bytes required by the read.
66 needed: usize,
67 /// Number of bytes available from `offset`.
68 available: usize,
69 },
70
71 /// The dictionary magic bytes were invalid.
72 #[error("invalid {format} magic: found {found:02x?}")]
73 InvalidMagic {
74 /// Dictionary format being parsed.
75 format: Format,
76 /// Magic bytes found in the input.
77 found: Vec<u8>,
78 },
79
80 /// The container variant was not supported.
81 #[error("unsupported {format} variant: found {found:02x?}")]
82 UnsupportedVariant {
83 /// Dictionary format being parsed.
84 format: Format,
85 /// Variant bytes found in the input.
86 found: Vec<u8>,
87 },
88
89 /// The format version was not supported.
90 #[error("unsupported {format} version: found {found:02x?}")]
91 UnsupportedVersion {
92 /// Dictionary format being parsed.
93 format: Format,
94 /// Version bytes found in the input.
95 found: Vec<u8>,
96 },
97
98 /// A UTF-16LE field declared an odd number of bytes.
99 #[error("{field} in {format} data at byte {offset:#x} has odd UTF-16LE byte length {length}")]
100 OddUtf16ByteLength {
101 /// Dictionary format being parsed.
102 format: Format,
103 /// Name of the field being parsed.
104 field: &'static str,
105 /// Offset of the field contents.
106 offset: usize,
107 /// Declared byte length.
108 length: usize,
109 },
110
111 /// A field contained invalid UTF-16.
112 #[error("invalid UTF-16LE in {format} field `{field}` at byte {offset:#x}: {source}")]
113 InvalidUtf16 {
114 /// Dictionary format being parsed.
115 format: Format,
116 /// Name of the field being parsed.
117 field: &'static str,
118 /// Offset of the field contents.
119 offset: usize,
120 /// Underlying UTF-16 decoder error.
121 #[source]
122 source: DecodeUtf16Error,
123 },
124
125 /// A field contained invalid UTF-8.
126 #[error("invalid UTF-8 in {format} field `{field}` at byte {offset:#x}: {source}")]
127 InvalidUtf8 {
128 /// Dictionary format being parsed.
129 format: Format,
130 /// Name of the field being parsed.
131 field: &'static str,
132 /// Offset of the field contents.
133 offset: usize,
134 /// Underlying UTF-8 decoder error.
135 #[source]
136 source: Utf8Error,
137 },
138
139 /// A field declared as ASCII contained a non-ASCII byte.
140 #[error("invalid ASCII byte {byte:#04x} in {format} field `{field}` at byte {offset:#x}")]
141 InvalidAscii {
142 /// Dictionary format being parsed.
143 format: Format,
144 /// Name of the field being parsed.
145 field: &'static str,
146 /// Byte offset of the invalid value.
147 offset: usize,
148 /// Invalid byte value.
149 byte: u8,
150 },
151
152 /// A compressed data section could not be decoded.
153 #[error(
154 "failed to decompress {format} data at byte {offset:#x}: zlib returned status {status}"
155 )]
156 InvalidCompression {
157 /// Dictionary format being parsed.
158 format: Format,
159 /// Byte offset of the compressed section in the source file.
160 offset: usize,
161 /// Numeric zlib return status.
162 status: i32,
163 },
164
165 /// A declared byte offset was outside its valid section.
166 #[error(
167 "invalid {field} offset {offset:#x} in {format} data: expected {minimum:#x}..={maximum:#x}"
168 )]
169 InvalidOffset {
170 /// Dictionary format being parsed.
171 format: Format,
172 /// Name of the offset field.
173 field: &'static str,
174 /// Declared byte offset.
175 offset: usize,
176 /// Smallest valid byte offset.
177 minimum: usize,
178 /// Largest valid byte offset.
179 maximum: usize,
180 },
181
182 /// A decoded section size disagreed with the source declaration.
183 #[error("{field} size mismatch in {format} data: expected {expected}, decoded {actual}")]
184 SizeMismatch {
185 /// Dictionary format being parsed.
186 format: Format,
187 /// Name of the measured section.
188 field: &'static str,
189 /// Size declared by the source.
190 expected: u64,
191 /// Size produced while parsing.
192 actual: u64,
193 },
194
195 /// Memory for a declared section could not be reserved.
196 #[error("failed to reserve {requested} items for {field} while parsing {format}: {source}")]
197 AllocationFailed {
198 /// Dictionary format being parsed.
199 format: Format,
200 /// Name of the allocation target.
201 field: &'static str,
202 /// Number of items requested.
203 requested: usize,
204 /// Underlying allocation error.
205 #[source]
206 source: TryReserveError,
207 },
208
209 /// A declared count cannot fit in the remaining input.
210 #[error(
211 "invalid {field} count {count} in {format} data: at most {maximum} records fit in the remaining data"
212 )]
213 InvalidCount {
214 /// Dictionary format being parsed.
215 format: Format,
216 /// Name of the count field.
217 field: &'static str,
218 /// Declared count.
219 count: u64,
220 /// Maximum count possible from the remaining bytes.
221 maximum: u64,
222 },
223
224 /// A code table contains the same identifier more than once.
225 #[error("duplicate code index {index} in {format} data")]
226 DuplicateCodeIndex {
227 /// Dictionary format being parsed.
228 format: Format,
229 /// Duplicate code identifier.
230 index: u64,
231 },
232
233 /// A dictionary entry refers to an identifier absent from its code table.
234 #[error("undefined code index {index} in {format} data at byte {offset:#x}")]
235 InvalidCodeIndex {
236 /// Dictionary format being parsed.
237 format: Format,
238 /// Unknown code identifier.
239 index: u64,
240 /// Byte offset of the reference.
241 offset: usize,
242 },
243
244 /// A component of an encoded syllable was outside its lookup table.
245 #[error("invalid {field} index {index} in {format} data at byte {offset:#x}")]
246 InvalidCodeComponent {
247 /// Dictionary format being parsed.
248 format: Format,
249 /// Component lookup table, such as `initial` or `final`.
250 field: &'static str,
251 /// Invalid lookup-table index.
252 index: u64,
253 /// Byte offset of the invalid index.
254 offset: usize,
255 },
256
257 /// A record header did not match any supported layout.
258 #[error("invalid {format} {field} record header at byte {offset:#x}: found {found:02x?}")]
259 InvalidRecordHeader {
260 /// Dictionary format being parsed.
261 format: Format,
262 /// Kind of record whose header was invalid.
263 field: &'static str,
264 /// Byte offset of the record header.
265 offset: usize,
266 /// Header bytes found in the input.
267 found: Vec<u8>,
268 },
269
270 /// A record field is shorter than the format requires.
271 #[error(
272 "invalid {field} length {length} in {format} data at byte {offset:#x}: at least {minimum} bytes are required"
273 )]
274 InvalidExtensionLength {
275 /// Dictionary format being parsed.
276 format: Format,
277 /// Name of the extension field.
278 field: &'static str,
279 /// Byte offset of the length field.
280 offset: usize,
281 /// Declared extension length.
282 length: usize,
283 /// Minimum length required by the format.
284 minimum: usize,
285 },
286
287 /// A parsed item count disagrees with its declared count.
288 #[error("{field} count mismatch in {format} data: expected {expected}, parsed {actual}")]
289 CountMismatch {
290 /// Dictionary format being parsed.
291 format: Format,
292 /// Name of the counted item.
293 field: &'static str,
294 /// Count declared by the source.
295 expected: u64,
296 /// Number of items actually parsed.
297 actual: u64,
298 },
299}
300
301/// Result type used by all dictionary parsers.
302pub type Result<T> = std::result::Result<T, Error>;