Skip to main content

msoffice_crypto/
file_params.rs

1//! What [`crate::Error::BadParameters`] carries: which field a file declares
2//! wrongly, the value it declares, and what was allowed — and what
3//! [`crate::Error::InvariantViolated`] names instead when the fault is ours.
4//!
5//! **No byte of the file is in either.** Every payload is a fieldless enum or
6//! an integer, and every `Display` renders only those (the owner, 2026-10-19;
7//! plan `docs/plans/msoffice-crypto-structured-bad-parameters-2026-10-19.md`).
8//! A consumer writes its own sentence from `got` and `max`: *"this file declares
9//! a spinCount of 12,000,000; the format allows at most 10,000,000"*.
10//!
11//! Under `crypto-ops`, with the `Error` that carries it. The detection build's one
12//! refusal, a stream over its read cap, is `Error::StreamTooLarge`.
13//!
14//! The write side's `EncryptParamProblem` is not reused: its wording speaks to a
15//! caller about a tuple they chose, and "whose number it is" is the reason the
16//! two variants are separate. They share the `limits.rs` taxonomy, not a type
17//! ([`Bound`]).
18
19/// Which field of the file a [`crate::Error::BadParameters`] is about.
20///
21/// Named in the specification's own spelling. Where the format carries two
22/// copies of one field (agile `keyData` and `p:encryptedKey`), each has its own
23/// entry.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum FileField {
27    // ── Agile EncryptionInfo ([MS-OFFCRYPTO] 2.3.4.10) ──
28    /// The agile EncryptionInfo's `Reserved` field.
29    AgileReserved,
30    /// `p:encryptedKey/@spinCount`.
31    SpinCount,
32    /// `keyData/@keyBits`.
33    KeyDataKeyBits,
34    /// `p:encryptedKey/@keyBits`.
35    EncryptedKeyKeyBits,
36    /// `keyData/@blockSize`.
37    KeyDataBlockSize,
38    /// `p:encryptedKey/@blockSize`.
39    EncryptedKeyBlockSize,
40    /// `keyData/@hashSize`.
41    KeyDataHashSize,
42    /// `p:encryptedKey/@hashSize`.
43    EncryptedKeyHashSize,
44    /// `keyData/@saltSize`.
45    KeyDataSaltSize,
46    /// `p:encryptedKey/@saltSize`.
47    EncryptedKeySaltSize,
48    /// `keyData/@saltValue`, its decoded length.
49    KeyDataSaltValue,
50    /// `p:encryptedKey/@saltValue`, its decoded length.
51    EncryptedKeySaltValue,
52    /// `keyData/@hashAlgorithm`.
53    KeyDataHashAlgorithm,
54    /// `p:encryptedKey/@hashAlgorithm`.
55    EncryptedKeyHashAlgorithm,
56    /// `keyData/@cipherAlgorithm`.
57    KeyDataCipherAlgorithm,
58    /// `p:encryptedKey/@cipherAlgorithm`.
59    EncryptedKeyCipherAlgorithm,
60    /// `keyData/@cipherChaining`.
61    KeyDataCipherChaining,
62    /// `p:encryptedKey/@cipherChaining`.
63    EncryptedKeyCipherChaining,
64    /// `p:encryptedKey/@encryptedKeyValue`, its decoded length.
65    EncryptedKeyValue,
66    /// `p:encryptedKey/@encryptedVerifierHashInput`, its decoded length.
67    EncryptedVerifierHashInput,
68    /// `p:encryptedKey/@encryptedVerifierHashValue`, its decoded length.
69    EncryptedVerifierHashValue,
70    /// The `keyEncryptor` / `p:encryptedKey` elements.
71    PasswordKeyEncryptor,
72    /// The `dataIntegrity` element.
73    DataIntegrity,
74    /// `dataIntegrity/@encryptedHmacKey`, its decoded length.
75    EncryptedHmacKey,
76    /// `dataIntegrity/@encryptedHmacValue`, its decoded length.
77    EncryptedHmacValue,
78    /// The session key `keyData/@keyBits` describes, as recovered.
79    SessionKey,
80
81    // ── Binary EncryptionInfo: standard and CryptoAPI (2.3.2, 2.3.3, 2.3.5.1) ──
82    /// The binary EncryptionInfo as a whole: its fixed prefix.
83    EncryptionInfo,
84    /// `EncryptionHeaderSize`.
85    EncryptionHeaderSize,
86    /// The `EncryptionHeader` structure's fixed fields.
87    EncryptionHeader,
88    /// `EncryptionHeader.Flags`.
89    EncryptionHeaderFlags,
90    /// `EncryptionHeader.KeySize`.
91    EncryptionHeaderKeySize,
92    /// `EncryptionHeader.AlgID`.
93    EncryptionHeaderAlgId,
94    /// The `EncryptionVerifier` structure.
95    EncryptionVerifier,
96    /// `EncryptionVerifier.SaltSize`.
97    VerifierSaltSize,
98    /// `EncryptionVerifier.VerifierHashSize`.
99    VerifierHashSize,
100    /// `EncryptedPackage`'s `StreamSize`.
101    EncryptedPackageSize,
102    /// The Office 97/2000 RC4 header (2.3.6.1).
103    Rc4Office97Header,
104
105    // ── Word 97 ([MS-DOC]) ──
106    /// `FibBase.wIdent`.
107    FibWIdent,
108    /// `FibBase.lKey`.
109    FibLKey,
110    /// The `EncryptionVersionInfo` a FIB or FILEPASS points at.
111    EncryptionVersionInfo,
112
113    // ── Excel 97 ([MS-XLS]) ──
114    /// A BIFF record header.
115    BiffRecord,
116    /// The Workbook stream's opening BOF record.
117    WorkbookBof,
118    /// The FILEPASS record.
119    Filepass,
120    /// `FILEPASS.wEncryptionType`.
121    FilepassEncryptionType,
122
123    // ── PowerPoint 97 ([MS-PPT], [MS-ODRAW]) ──
124    /// The `UserEditAtom`.
125    UserEditAtom,
126    /// `UserEditAtom.offsetLastEdit`.
127    OffsetLastEdit,
128    /// The `PersistDirectoryAtom`.
129    PersistDirectory,
130    /// `UserEditAtom.encryptSessionPersistIdRef`.
131    EncryptSessionPersistIdRef,
132    /// The `CryptSession10Container`.
133    CryptSession10Container,
134    /// A persist object's offset.
135    PersistObject,
136    /// A record of the `Pictures` stream.
137    PicturesRecord,
138
139    // ── The encrypted summary stream (2.3.5.4) ──
140    /// The `encryption` stream as a whole.
141    SummaryStream,
142    /// The `EncryptedStreamDescriptor` array.
143    SummaryDescriptorArray,
144    /// `EncryptedStreamDescriptorCount`.
145    SummaryDescriptorCount,
146    /// One `EncryptedStreamDescriptor`.
147    SummaryDescriptor,
148    /// An `EncryptedStreamDescriptor`'s stream name.
149    SummaryStreamName,
150    /// An encrypted stream's extent.
151    SummaryStreamExtent,
152}
153
154impl FileField {
155    /// The field's spelling, as the specification writes it.
156    pub fn spelling(self) -> &'static str {
157        // Exhaustive, with no `_` arm: a new field fails to compile here until it
158        // is given its spelling.
159        match self {
160            Self::AgileReserved => "agile EncryptionInfo Reserved",
161            Self::SpinCount => "p:encryptedKey/@spinCount",
162            Self::KeyDataKeyBits => "keyData/@keyBits",
163            Self::EncryptedKeyKeyBits => "p:encryptedKey/@keyBits",
164            Self::KeyDataBlockSize => "keyData/@blockSize",
165            Self::EncryptedKeyBlockSize => "p:encryptedKey/@blockSize",
166            Self::KeyDataHashSize => "keyData/@hashSize",
167            Self::EncryptedKeyHashSize => "p:encryptedKey/@hashSize",
168            Self::KeyDataSaltSize => "keyData/@saltSize",
169            Self::EncryptedKeySaltSize => "p:encryptedKey/@saltSize",
170            Self::KeyDataSaltValue => "keyData/@saltValue",
171            Self::EncryptedKeySaltValue => "p:encryptedKey/@saltValue",
172            Self::KeyDataHashAlgorithm => "keyData/@hashAlgorithm",
173            Self::EncryptedKeyHashAlgorithm => "p:encryptedKey/@hashAlgorithm",
174            Self::KeyDataCipherAlgorithm => "keyData/@cipherAlgorithm",
175            Self::EncryptedKeyCipherAlgorithm => "p:encryptedKey/@cipherAlgorithm",
176            Self::KeyDataCipherChaining => "keyData/@cipherChaining",
177            Self::EncryptedKeyCipherChaining => "p:encryptedKey/@cipherChaining",
178            Self::EncryptedKeyValue => "p:encryptedKey/@encryptedKeyValue",
179            Self::EncryptedVerifierHashInput => "p:encryptedKey/@encryptedVerifierHashInput",
180            Self::EncryptedVerifierHashValue => "p:encryptedKey/@encryptedVerifierHashValue",
181            Self::PasswordKeyEncryptor => "keyEncryptor (password)",
182            Self::DataIntegrity => "dataIntegrity",
183            Self::EncryptedHmacKey => "dataIntegrity/@encryptedHmacKey",
184            Self::EncryptedHmacValue => "dataIntegrity/@encryptedHmacValue",
185            Self::SessionKey => "the recovered session key",
186            Self::EncryptionInfo => "EncryptionInfo",
187            Self::EncryptionHeaderSize => "EncryptionHeaderSize",
188            Self::EncryptionHeader => "EncryptionHeader",
189            Self::EncryptionHeaderFlags => "EncryptionHeader.Flags",
190            Self::EncryptionHeaderKeySize => "EncryptionHeader.KeySize",
191            Self::EncryptionHeaderAlgId => "EncryptionHeader.AlgID",
192            Self::EncryptionVerifier => "EncryptionVerifier",
193            Self::VerifierSaltSize => "EncryptionVerifier.SaltSize",
194            Self::VerifierHashSize => "EncryptionVerifier.VerifierHashSize",
195            Self::EncryptedPackageSize => "EncryptedPackage StreamSize",
196            Self::Rc4Office97Header => "the RC4 (Office 97) header",
197            Self::FibWIdent => "FibBase.wIdent",
198            Self::FibLKey => "FibBase.lKey",
199            Self::EncryptionVersionInfo => "EncryptionVersionInfo",
200            Self::BiffRecord => "a BIFF record",
201            Self::WorkbookBof => "the Workbook BOF record",
202            Self::Filepass => "the FILEPASS record",
203            Self::FilepassEncryptionType => "FILEPASS.wEncryptionType",
204            Self::UserEditAtom => "the UserEditAtom",
205            Self::OffsetLastEdit => "UserEditAtom.offsetLastEdit",
206            Self::PersistDirectory => "the PersistDirectoryAtom",
207            Self::EncryptSessionPersistIdRef => "UserEditAtom.encryptSessionPersistIdRef",
208            Self::CryptSession10Container => "the CryptSession10Container",
209            Self::PersistObject => "a persist object",
210            Self::PicturesRecord => "a Pictures record",
211            Self::SummaryStream => "the encrypted summary stream",
212            Self::SummaryDescriptorArray => "the EncryptedStreamDescriptor array",
213            Self::SummaryDescriptorCount => "EncryptedStreamDescriptorCount",
214            Self::SummaryDescriptor => "an EncryptedStreamDescriptor",
215            Self::SummaryStreamName => "an EncryptedStreamDescriptor's stream name",
216            Self::SummaryStreamExtent => "an encrypted stream's extent",
217        }
218    }
219}
220
221impl core::fmt::Display for FileField {
222    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
223        f.write_str(self.spelling())
224    }
225}
226
227/// Whose number a range or required value is: the `limits.rs` taxonomy,
228/// phrased for a file. A test holds every `limits.rs` label to a variant.
229#[derive(Debug, Clone, Copy, PartialEq, Eq)]
230#[non_exhaustive]
231pub enum Bound {
232    /// The specification states it ([MS-OFFCRYPTO], [MS-DOC], [MS-XLS],
233    /// [MS-PPT], ECMA-376).
234    Spec,
235    /// The cipher or hash cannot run anything else (an AES block of 16 bytes).
236    Cipher,
237    /// A margin of this crate's, above anything Office writes.
238    Margin,
239    /// A choice of this crate's that is not a margin, such as refusing to pad a
240    /// key with 0x36 bytes.
241    Crate,
242}
243
244impl core::fmt::Display for Bound {
245    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
246        f.write_str(match self {
247            Self::Spec => "the specification's",
248            Self::Cipher => "the cipher's",
249            Self::Margin => "this crate's margin",
250            Self::Crate => "this crate's",
251        })
252    }
253}
254
255/// A closed set of allowed values, so a set is never printed as a range.
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257#[non_exhaustive]
258pub enum AllowedSet {
259    /// AES key sizes in bits: 128, 192, 256.
260    AesKeyBits,
261    /// `FILEPASS.wEncryptionType`: 0 (XOR) or 1 (RC4).
262    XorOrRc4,
263    /// RC4 CryptoAPI key sizes in bits: 40 to 128 in steps of 8.
264    Rc4KeyBits,
265    /// `Pictures` record types: a blip or a file-block entry.
266    PicturesRecordTypes,
267}
268
269impl core::fmt::Display for AllowedSet {
270    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
271        f.write_str(match self {
272            Self::AesKeyBits => "128, 192 or 256",
273            Self::XorOrRc4 => "0 (XOR) or 1 (RC4)",
274            Self::Rc4KeyBits => "40 to 128 in steps of 8",
275            Self::PicturesRecordTypes => "a blip or a file-block entry",
276        })
277    }
278}
279
280/// What is wrong with a [`FileField`]. Integers and closed enums only.
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
282#[non_exhaustive]
283pub enum FileProblem {
284    /// Outside an inclusive range.
285    OutOfRange {
286        /// The value the file declares.
287        got: u64,
288        /// Inclusive floor.
289        min: u64,
290        /// Inclusive ceiling.
291        max: u64,
292        /// Whose range it is.
293        bound: Bound,
294    },
295    /// Not one of a closed set of values.
296    NotInSet {
297        /// The value the file declares.
298        got: u64,
299        /// The values allowed.
300        allowed: AllowedSet,
301        /// Whose set it is.
302        bound: Bound,
303    },
304    /// Not the one value allowed.
305    NotRequiredValue {
306        /// The value the file declares.
307        got: u64,
308        /// The value required.
309        required: u64,
310        /// Whose requirement it is.
311        bound: Bound,
312    },
313    /// Disagrees with another value the file declares or holds.
314    Disagrees {
315        /// The value of this field.
316        got: u64,
317        /// What the other field implies it must be.
318        expected: u64,
319        /// The other field.
320        with: FileField,
321    },
322    /// A length or bit count the named hash cannot produce or take.
323    DigestMismatch {
324        /// The value the file declares.
325        got: u64,
326        /// The hash the file names.
327        hash: crate::HashAlgorithm,
328    },
329    /// Fewer bytes than the structure needs.
330    Truncated {
331        /// The bytes there are.
332        have: u64,
333        /// The bytes it needs.
334        need: u64,
335    },
336    /// An extent runs past the end of what holds it.
337    OutOfBounds {
338        /// Where it starts.
339        offset: u64,
340        /// How long it is.
341        len: u64,
342        /// Where what holds it ends.
343        end: u64,
344    },
345    /// Cannot be read where it starts: no whole header, or a length past the end.
346    Unreadable {
347        /// Where it starts.
348        offset: u64,
349    },
350    /// Required and absent.
351    Missing,
352    /// Present more than once where the format allows one.
353    Duplicate,
354    /// Overlaps another extent.
355    Overlaps,
356    /// A string that is not terminated.
357    Unterminated,
358    /// A flag the format requires is clear.
359    FlagClear,
360    /// A signature or identifier is not the format's.
361    BadSignature,
362    /// In the wrong place in a sequence.
363    OutOfOrder {
364        /// The record it follows.
365        after_record: u16,
366    },
367    /// A value the format does not define.
368    Unrecognized {
369        /// The value the file declares.
370        got: u64,
371    },
372}
373
374impl core::fmt::Display for FileProblem {
375    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
376        match self {
377            Self::OutOfRange {
378                got,
379                min,
380                max,
381                bound,
382            } => write!(f, "is {got}, outside {min}..={max} ({bound} range)"),
383            Self::NotInSet {
384                got,
385                allowed,
386                bound,
387            } => write!(f, "is {got}, not {allowed} ({bound} set)"),
388            Self::NotRequiredValue {
389                got,
390                required,
391                bound,
392            } => write!(f, "is {got}, not {required} ({bound} requirement)"),
393            Self::Disagrees {
394                got,
395                expected,
396                with,
397            } => write!(f, "is {got}, but {with} requires {expected}"),
398            Self::DigestMismatch { got, hash } => {
399                write!(f, "is {got}, which {} cannot produce", hash.name())
400            }
401            Self::Truncated { have, need } => write!(f, "is {have} bytes, needs {need}"),
402            Self::OutOfBounds { offset, len, end } => {
403                write!(f, "runs from {offset} for {len} bytes, past {end}")
404            }
405            Self::Unreadable { offset } => write!(f, "cannot be read at offset {offset}"),
406            Self::Missing => f.write_str("is missing"),
407            Self::Duplicate => f.write_str("appears more than once"),
408            Self::Overlaps => f.write_str("overlaps another"),
409            Self::Unterminated => f.write_str("is not terminated"),
410            Self::FlagClear => f.write_str("has a required flag clear"),
411            Self::BadSignature => f.write_str("does not carry the format's signature"),
412            Self::OutOfOrder { after_record } => {
413                write!(f, "follows record 0x{after_record:04X}")
414            }
415            Self::Unrecognized { got } => write!(f, "is {got}, a value the format does not define"),
416        }
417    }
418}
419
420/// An invariant of this crate's that something upstream should have enforced:
421/// reaching one is a bug here, not a property of the file
422/// ([`crate::Error::InvariantViolated`]).
423#[derive(Debug, Clone, Copy, PartialEq, Eq)]
424#[non_exhaustive]
425pub enum Invariant {
426    /// An AES key the cipher would not take reached it.
427    AesKeyLength,
428    /// An AES IV the cipher would not take reached it.
429    AesIvLength,
430    /// A block size larger than the digest reached IV derivation.
431    BlockSizeOverDigest,
432    /// More segments or blocks than a 32-bit counter numbers.
433    CounterOverflow,
434    /// An in-place rewrite changed a stream's length.
435    RewriteLength,
436    /// An EncryptionInfo placeholder changed length on rewrite.
437    PlaceholderLength,
438    /// A serializer produced a blob of the wrong length.
439    SerializedLength,
440    /// Integrity sealing reached padding arithmetic that cannot hold.
441    IntegrityPadding,
442    /// An RC4 key outside 5..=16 bytes reached the key schedule.
443    Rc4KeyLength,
444    /// An RC4 block size of zero reached the block loop.
445    Rc4BlockSize,
446    /// A key size the screen refuses reached the SHA-1 key ladder.
447    KeyLadderLength,
448    /// A value from the file does not fit this host's `usize`.
449    Unrepresentable,
450    /// A slice of our own computation fell outside its buffer.
451    InternalSlice,
452}
453
454impl core::fmt::Display for Invariant {
455    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
456        f.write_str(match self {
457            Self::AesKeyLength => "an AES key length the screen passed",
458            Self::AesIvLength => "an AES IV length the screen passed",
459            Self::BlockSizeOverDigest => "a block size longer than its digest",
460            Self::CounterOverflow => "more blocks than a 32-bit counter numbers",
461            Self::RewriteLength => "an in-place rewrite changed a stream's length",
462            Self::PlaceholderLength => "the EncryptionInfo placeholder changed length",
463            Self::SerializedLength => "a serialized blob has the wrong length",
464            Self::IntegrityPadding => "integrity padding arithmetic overflowed",
465            Self::Rc4KeyLength => "an RC4 key length outside 5..=16 bytes",
466            Self::Rc4BlockSize => "an RC4 block size of zero",
467            Self::KeyLadderLength => "a key size the SHA-1 ladder cannot yield",
468            Self::Unrepresentable => "a value that does not fit this host's usize",
469            Self::InternalSlice => "a slice outside its buffer",
470        })
471    }
472}
473
474/// What [`crate::Error::UnsupportedAlgorithm`] names: never the file's own text.
475///
476/// Until 0.1.0-rc.9 the agile path put the file's spelling here, truncated to
477/// 32 characters: text the file chose. A name [MS-OFFCRYPTO] §2.3.4.10 defines
478/// is now one of [`KnownAlgorithm`], and any other is only its length.
479#[derive(Debug, Clone, Copy, PartialEq, Eq)]
480#[non_exhaustive]
481pub enum AlgorithmName {
482    /// A name the specification defines and this crate does not implement.
483    Known(KnownAlgorithm),
484    /// A name the specification does not define, by its length in characters.
485    Unknown {
486        /// How many characters the file's name has.
487        len: u32,
488    },
489    /// A binary `AlgID` or `AlgIDHash` value.
490    AlgId(u32),
491    /// A fixed description this crate wrote of what was refused.
492    Fixed(&'static str),
493}
494
495impl core::fmt::Display for AlgorithmName {
496    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
497        match self {
498            Self::Known(k) => write!(f, "{k}"),
499            Self::Unknown { len } => {
500                write!(f, "a name the format does not define ({len} characters)")
501            }
502            Self::AlgId(id) => write!(f, "{id:#010x}"),
503            Self::Fixed(s) => f.write_str(s),
504        }
505    }
506}
507
508/// An algorithm or chaining mode [MS-OFFCRYPTO] §2.3.4.10 names that this
509/// crate does not implement, which the format permits ("a compliant
510/// implementation is not required to support all defined values").
511#[derive(Debug, Clone, Copy, PartialEq, Eq)]
512#[non_exhaustive]
513pub enum KnownAlgorithm {
514    /// `MD5`.
515    Md5,
516    /// `MD4`.
517    Md4,
518    /// `MD2`.
519    Md2,
520    /// `RIPEMD-128`.
521    Ripemd128,
522    /// `RIPEMD-160`.
523    Ripemd160,
524    /// `WHIRLPOOL`.
525    Whirlpool,
526    /// `RC2`.
527    Rc2,
528    /// `RC4`.
529    Rc4,
530    /// `DES`.
531    Des,
532    /// `DESX`.
533    Desx,
534    /// `3DES`.
535    TripleDes,
536    /// `3DES_112`.
537    TripleDes112,
538    /// `ChainingModeCFB`.
539    ChainingModeCfb,
540}
541
542impl KnownAlgorithm {
543    const ALL: [KnownAlgorithm; 13] = [
544        Self::Md5,
545        Self::Md4,
546        Self::Md2,
547        Self::Ripemd128,
548        Self::Ripemd160,
549        Self::Whirlpool,
550        Self::Rc2,
551        Self::Rc4,
552        Self::Des,
553        Self::Desx,
554        Self::TripleDes,
555        Self::TripleDes112,
556        Self::ChainingModeCfb,
557    ];
558
559    /// The specification's spelling.
560    pub fn spelling(self) -> &'static str {
561        match self {
562            Self::Md5 => "MD5",
563            Self::Md4 => "MD4",
564            Self::Md2 => "MD2",
565            Self::Ripemd128 => "RIPEMD-128",
566            Self::Ripemd160 => "RIPEMD-160",
567            Self::Whirlpool => "WHIRLPOOL",
568            Self::Rc2 => "RC2",
569            Self::Rc4 => "RC4",
570            Self::Des => "DES",
571            Self::Desx => "DESX",
572            Self::TripleDes => "3DES",
573            Self::TripleDes112 => "3DES_112",
574            Self::ChainingModeCfb => "ChainingModeCFB",
575        }
576    }
577}
578
579impl core::fmt::Display for KnownAlgorithm {
580    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
581        f.write_str(self.spelling())
582    }
583}
584
585/// The closed name for a spelling the file chose: a [`KnownAlgorithm`] matched
586/// exactly (case-sensitively, as `HashAlgorithm::parse` matches), else its
587/// length.
588pub(crate) fn algorithm_name(spelled: &str) -> AlgorithmName {
589    KnownAlgorithm::ALL
590        .into_iter()
591        .find(|k| k.spelling() == spelled)
592        .map_or_else(
593            || AlgorithmName::Unknown {
594                len: u32::try_from(spelled.chars().count()).unwrap_or(u32::MAX),
595            },
596            AlgorithmName::Known,
597        )
598}
599
600/// `n` as a `u64`, saturating: a length that does not fit is reported as
601/// `u64::MAX` rather than panicking.
602pub(crate) fn wide<T: TryInto<u64>>(n: T) -> u64 {
603    n.try_into().unwrap_or(u64::MAX)
604}
605
606/// The refusal for `field` with `problem`.
607pub(crate) fn bad(field: FileField, problem: FileProblem) -> crate::Error {
608    crate::Error::BadParameters { field, problem }
609}