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)]
46pub enum PemLineEnding {
47    /// Unix line endings.
48    Lf,
49    /// Network/Windows line endings.
50    Crlf,
51}
52
53impl PemLineEnding {
54    pub(crate) const fn as_str(self) -> &'static str {
55        match self {
56            Self::Lf => "\n",
57            Self::Crlf => "\r\n",
58        }
59    }
60}
61
62/// Options controlling PEM encoding.
63#[derive(Debug, Clone, Copy)]
64pub struct PemEncodeOptions {
65    /// Maximum DER body length accepted for encoding.
66    pub max_der_len: usize,
67    /// Base64 body line width.
68    pub line_width: usize,
69    /// Line ending to emit.
70    pub line_ending: PemLineEnding,
71}
72
73impl Default for PemEncodeOptions {
74    fn default() -> Self {
75        Self {
76            max_der_len: DEFAULT_MAX_DER_LEN,
77            line_width: DEFAULT_PEM_LINE_WIDTH,
78            line_ending: PemLineEnding::Lf,
79        }
80    }
81}