Skip to main content

rnp_sexp/
lib.rs

1//! Pure-Rust S-expression parser and serializer for OpenPGP key formats.
2//!
3//! A faithful port of librnp's `sexpp` C++ library. Supports canonical,
4//! advanced, and base64 printing modes plus the GnuPG 2.3+ extended private key
5//! format.
6//!
7//! ```
8//! use rnp_sexp::Sexp;
9//!
10//! let input = "(8:test-key (1:a 3:bcd))";
11//! let sexp = Sexp::parse_advanced(input).unwrap();
12//! println!("{}", sexp.to_advanced());
13//! ```
14
15mod chars;
16mod depth;
17pub mod error;
18mod ext_key;
19mod input;
20mod output;
21
22pub use error::{Severity, SexpError};
23pub use ext_key::{parse_extended, ExtKeyInputStream, ExtendedPrivateKey};
24pub use input::{CharSource, SexpInputStream, SliceSource};
25pub use output::{PrintMode, SexpOutputStream};
26
27/// An S-expression value: either a list or a string.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum Sexp {
30    List(SexpList),
31    String(SexpString),
32}
33
34/// An S-expression list: `(elem1 elem2 ...)`.
35#[derive(Debug, Clone, PartialEq, Eq, Default)]
36pub struct SexpList {
37    pub elements: Vec<Sexp>,
38}
39
40/// An S-expression string: raw bytes with an optional presentation hint.
41#[derive(Debug, Clone, PartialEq, Eq, Default)]
42pub struct SexpString {
43    pub data: Vec<u8>,
44    pub presentation_hint: Option<Vec<u8>>,
45}
46
47impl Sexp {
48    pub fn list(elements: Vec<Sexp>) -> Self {
49        Sexp::List(SexpList { elements })
50    }
51
52    pub fn string(data: impl Into<Vec<u8>>) -> Self {
53        Sexp::String(SexpString {
54            data: data.into(),
55            presentation_hint: None,
56        })
57    }
58
59    pub fn is_list(&self) -> bool {
60        matches!(self, Sexp::List(_))
61    }
62
63    pub fn is_string(&self) -> bool {
64        matches!(self, Sexp::String(_))
65    }
66
67    pub fn as_list(&self) -> Option<&SexpList> {
68        match self {
69            Sexp::List(l) => Some(l),
70            _ => None,
71        }
72    }
73
74    pub fn as_string(&self) -> Option<&SexpString> {
75        match self {
76            Sexp::String(s) => Some(s),
77            _ => None,
78        }
79    }
80
81    pub fn parse_advanced(input: &str) -> Result<Self, SexpError> {
82        let mut is = SexpInputStream::new(input);
83        is.get_char()?;
84        is.scan_object()
85    }
86
87    pub fn parse_canonical(input: &[u8]) -> Result<Self, SexpError> {
88        let mut is = SexpInputStream::new(input);
89        is.get_char()?;
90        is.scan_object()
91    }
92
93    pub fn to_string_with_mode(&self, mode: PrintMode) -> String {
94        let mut os = SexpOutputStream::new();
95        match mode {
96            PrintMode::Canonical => os.print_canonical(self).ok(),
97            PrintMode::Advanced => os.print_advanced(self).ok(),
98            PrintMode::Base64 => os.print_base64(self).ok(),
99        };
100        os.into_string_lossy()
101    }
102
103    pub fn to_advanced(&self) -> String {
104        self.to_string_with_mode(PrintMode::Advanced)
105    }
106
107    pub fn to_canonical(&self) -> Vec<u8> {
108        let mut os = SexpOutputStream::new();
109        os.print_canonical(self).ok();
110        os.into_bytes()
111    }
112
113    pub fn to_base64(&self) -> String {
114        self.to_string_with_mode(PrintMode::Base64)
115    }
116
117    pub fn equals_str(&self, other: &str) -> bool {
118        match self {
119            Sexp::String(s) => s.equals_str(other),
120            _ => false,
121        }
122    }
123
124    /// Mirrors C++ `as_unsigned()`: returns u32::MAX if the data is empty or
125    /// not a valid decimal, otherwise the parsed value.
126    pub fn as_unsigned(&self) -> u32 {
127        match self {
128            Sexp::String(s) => s.as_unsigned(),
129            _ => u32::MAX,
130        }
131    }
132}
133
134impl SexpString {
135    pub fn new() -> Self {
136        Self::default()
137    }
138
139    pub fn from_bytes(data: impl Into<Vec<u8>>) -> Self {
140        SexpString {
141            data: data.into(),
142            presentation_hint: None,
143        }
144    }
145
146    pub fn from_string(s: &str) -> Self {
147        Self::from_bytes(s.as_bytes().to_vec())
148    }
149
150    pub fn as_bytes(&self) -> &[u8] {
151        &self.data
152    }
153
154    pub fn as_str(&self) -> Result<&str, std::str::Utf8Error> {
155        std::str::from_utf8(&self.data)
156    }
157
158    pub fn has_presentation_hint(&self) -> bool {
159        self.presentation_hint.is_some()
160    }
161
162    /// Mirrors C++ `as_unsigned()`: returns u32::MAX on empty or non-numeric
163    /// data, otherwise the parsed value.
164    pub fn as_unsigned(&self) -> u32 {
165        if self.data.is_empty() {
166            return u32::MAX;
167        }
168        let s = match std::str::from_utf8(&self.data) {
169            Ok(s) => s,
170            Err(_) => return u32::MAX,
171        };
172        s.parse::<u32>().unwrap_or(u32::MAX)
173    }
174
175    pub fn equals_str(&self, other: &str) -> bool {
176        self.data == other.as_bytes()
177    }
178}
179
180impl SexpList {
181    pub fn new() -> Self {
182        Self::default()
183    }
184
185    pub fn push(&mut self, elem: Sexp) {
186        self.elements.push(elem);
187    }
188
189    pub fn len(&self) -> usize {
190        self.elements.len()
191    }
192
193    pub fn is_empty(&self) -> bool {
194        self.elements.is_empty()
195    }
196
197    pub fn iter(&self) -> std::slice::Iter<'_, Sexp> {
198        self.elements.iter()
199    }
200
201    pub fn get(&self, idx: usize) -> Option<&Sexp> {
202        self.elements.get(idx)
203    }
204
205    pub fn sexp_list_at(&self, idx: usize) -> Option<&SexpList> {
206        self.elements.get(idx).and_then(|e| e.as_list())
207    }
208
209    pub fn sexp_string_at(&self, idx: usize) -> Option<&SexpString> {
210        self.elements.get(idx).and_then(|e| e.as_string())
211    }
212}
213
214impl std::ops::Index<usize> for SexpList {
215    type Output = Sexp;
216    fn index(&self, idx: usize) -> &Sexp {
217        &self.elements[idx]
218    }
219}
220
221// --- Top-level convenience functions (mirror upstream free functions) ---
222
223pub fn parse_advanced(input: &str) -> Result<Sexp, SexpError> {
224    Sexp::parse_advanced(input)
225}
226
227pub fn parse_canonical(input: &[u8]) -> Result<Sexp, SexpError> {
228    Sexp::parse_canonical(input)
229}