Skip to main content

codec_pem/
policy.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: 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] = &[
18    PemLabel::PrivateKey,
19    PemLabel::EcPrivateKey,
20    PemLabel::PublicKey,
21];
22
23/// Policy controlling PEM decoding.
24#[derive(Debug, Clone, Copy)]
25pub struct PemDecodePolicy<'a> {
26    /// Exact labels accepted by the caller.
27    pub allowed_labels: &'a [PemLabel],
28    /// Maximum input text length in bytes.
29    pub max_input_len: usize,
30    /// Maximum decoded DER body length in bytes.
31    pub max_der_len: usize,
32}
33
34impl Default for PemDecodePolicy<'_> {
35    fn default() -> Self {
36        Self {
37            allowed_labels: DEFAULT_ALLOWED_LABELS,
38            max_input_len: DEFAULT_MAX_PEM_INPUT_LEN,
39            max_der_len: DEFAULT_MAX_DER_LEN,
40        }
41    }
42}
43
44/// Line ending emitted by PEM encoding.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46#[non_exhaustive]
47pub enum PemLineEnding {
48    /// Unix line endings.
49    Lf,
50    /// Network/Windows line endings.
51    Crlf,
52}
53
54impl PemLineEnding {
55    pub(crate) const fn as_str(self) -> &'static str {
56        match self {
57            Self::Lf => "\n",
58            Self::Crlf => "\r\n",
59        }
60    }
61}
62
63/// Options controlling PEM encoding.
64#[derive(Debug, Clone, Copy)]
65pub struct PemEncodeOptions {
66    /// Maximum DER body length accepted for encoding.
67    pub max_der_len: usize,
68    /// Base64 body line width.
69    pub line_width: usize,
70    /// Line ending to emit.
71    pub line_ending: PemLineEnding,
72}
73
74impl Default for PemEncodeOptions {
75    fn default() -> Self {
76        Self {
77            max_der_len: DEFAULT_MAX_DER_LEN,
78            line_width: DEFAULT_PEM_LINE_WIDTH,
79            line_ending: PemLineEnding::Lf,
80        }
81    }
82}