Skip to main content

codec_pem/
policy.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe LLC
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use crate::PemLabel;
6
7/// Default maximum PEM input size accepted by the parser.
8pub const DEFAULT_MAX_PEM_INPUT_LEN: usize = 1024 * 1024;
9
10/// Default maximum decoded DER size accepted by the parser.
11pub const DEFAULT_MAX_DER_LEN: usize = 1024 * 1024;
12
13/// Default PEM body line width used by the encoder.
14pub const DEFAULT_PEM_LINE_WIDTH: usize = 64;
15
16/// Labels accepted by the default decode policy.
17pub const DEFAULT_ALLOWED_LABELS: &[PemLabel] = &[PemLabel::PublicKey];
18
19/// Policy controlling PEM decoding.
20#[derive(Debug, Clone, Copy)]
21pub struct PemDecodePolicy<'a> {
22    /// Exact labels accepted by the caller.
23    pub allowed_labels: &'a [PemLabel],
24    /// Maximum input text length in bytes.
25    pub max_input_len: usize,
26    /// Maximum decoded DER body length in bytes.
27    pub max_der_len: usize,
28}
29
30impl Default for PemDecodePolicy<'_> {
31    fn default() -> Self {
32        Self {
33            allowed_labels: DEFAULT_ALLOWED_LABELS,
34            max_input_len: DEFAULT_MAX_PEM_INPUT_LEN,
35            max_der_len: DEFAULT_MAX_DER_LEN,
36        }
37    }
38}
39
40/// Line ending emitted by PEM encoding.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum PemLineEnding {
44    /// Unix line endings.
45    Lf,
46    /// Network/Windows line endings.
47    Crlf,
48}
49
50impl PemLineEnding {
51    pub(crate) const fn as_str(self) -> &'static str {
52        match self {
53            Self::Lf => "\n",
54            Self::Crlf => "\r\n",
55        }
56    }
57}
58
59/// Options controlling PEM encoding.
60#[derive(Debug, Clone, Copy)]
61pub struct PemEncodeOptions {
62    /// Maximum DER body length accepted for encoding.
63    pub max_der_len: usize,
64    /// Base64 body line width.
65    pub line_width: usize,
66    /// Line ending to emit.
67    pub line_ending: PemLineEnding,
68}
69
70impl Default for PemEncodeOptions {
71    fn default() -> Self {
72        Self {
73            max_der_len: DEFAULT_MAX_DER_LEN,
74            line_width: DEFAULT_PEM_LINE_WIDTH,
75            line_ending: PemLineEnding::Lf,
76        }
77    }
78}