picky_asn1_der/ser/
mod.rs

1mod boolean;
2mod integer;
3mod null;
4mod sequence;
5mod utf8_string;
6
7use crate::misc::{Length, WriteExt};
8use crate::ser::boolean::Boolean;
9use crate::ser::integer::UnsignedInteger;
10use crate::ser::null::Null;
11use crate::ser::sequence::Sequence;
12use crate::ser::utf8_string::Utf8String;
13use crate::{Asn1DerError, Asn1RawDer, Result};
14use picky_asn1::Asn1Type;
15use picky_asn1::tag::Tag;
16use picky_asn1::wrapper::*;
17use serde::Serialize;
18use std::io::{Cursor, Write};
19
20/// Serializes `value`
21pub fn to_vec<T: ?Sized + Serialize>(value: &T) -> Result<Vec<u8>> {
22    let mut buf = Vec::new();
23    to_byte_buf(value, &mut buf)?;
24    Ok(buf)
25}
26
27/// Serializes `value` to `buf` and returns the amount of serialized bytes
28pub fn to_bytes<T: ?Sized + Serialize>(value: &T, buf: &mut [u8]) -> Result<usize> {
29    debug_log!("serialization using `to_bytes`");
30    let mut serializer = Serializer::new_to_bytes(buf);
31    value.serialize(&mut serializer)
32}
33
34/// Serializes `value` to `buf` and returns the amount of serialized bytes
35pub fn to_byte_buf<T: ?Sized + Serialize>(value: &T, buf: &mut Vec<u8>) -> Result<usize> {
36    debug_log!("serialization using `to_byte_buf`");
37    let mut serializer = Serializer::new_to_byte_buf(buf);
38    value.serialize(&mut serializer)
39}
40
41/// Serializes `value` to `writer` and returns the amount of serialized bytes
42pub fn to_writer<T: ?Sized + Serialize>(value: &T, writer: impl Write) -> Result<usize> {
43    debug_log!("serialization using `to_writer`");
44    let mut serializer = Serializer::new_to_writer(writer);
45    value.serialize(&mut serializer)
46}
47
48/// An ASN.1-DER serializer for `serde`
49pub struct Serializer<'se> {
50    writer: Box<dyn Write + 'se>,
51    tag_for_next_bytes: Tag,
52    tag_for_next_seq: Tag,
53    encapsulators: Vec<Tag>,
54    no_header: bool,
55}
56
57impl<'se> Serializer<'se> {
58    /// Creates a new serializer that writes to `buf`
59    pub fn new_to_bytes(buf: &'se mut [u8]) -> Self {
60        Self::new_to_writer(Cursor::new(buf))
61    }
62
63    /// Creates a new serializer that writes to `buf`
64    pub fn new_to_byte_buf(buf: &'se mut Vec<u8>) -> Self {
65        Self::new_to_writer(Cursor::new(buf))
66    }
67
68    /// Creates a new serializer that writes to `writer`
69    pub fn new_to_writer(writer: impl Write + 'se) -> Self {
70        Self {
71            writer: Box::new(writer),
72            tag_for_next_bytes: Tag::OCTET_STRING,
73            tag_for_next_seq: Tag::SEQUENCE,
74            encapsulators: Vec::with_capacity(3),
75            no_header: false,
76        }
77    }
78
79    fn h_encapsulate(&mut self, tag: Tag) {
80        self.encapsulators.push(tag);
81    }
82
83    fn h_write_encapsulator(&mut self, payload_len: usize) -> Result<usize> {
84        let mut written = 0;
85
86        for (i, encapsulator_tag) in self.encapsulators.iter().copied().enumerate() {
87            written += self.writer.write_one(encapsulator_tag.inner())?;
88
89            let encapsulated_len = {
90                let mut encapsulated_len = payload_len;
91                for sub_encapsulator_tag in self.encapsulators.iter().skip(i + 1).copied().rev() {
92                    if sub_encapsulator_tag == BitStringAsn1Container::<()>::TAG {
93                        encapsulated_len += Length::encoded_len(encapsulated_len + 1) + 1;
94                    } else {
95                        encapsulated_len += Length::encoded_len(encapsulated_len) + 1;
96                    }
97                }
98                encapsulated_len
99            };
100
101            if encapsulator_tag == BitStringAsn1Container::<()>::TAG {
102                written += Length::serialize(encapsulated_len + 1, &mut self.writer)?;
103                written += self.writer.write_one(0x00)?; // no unused bits
104            } else {
105                written += Length::serialize(encapsulated_len, &mut self.writer)?;
106            }
107        }
108
109        self.encapsulators.clear();
110
111        Ok(written)
112    }
113
114    fn h_write_header(&mut self, tag: Tag, len: usize) -> Result<usize> {
115        let mut written;
116        match self.encapsulators.last() {
117            Some(last_encapsulator_tag)
118                if last_encapsulator_tag.is_context_specific() && last_encapsulator_tag.is_primitive() =>
119            {
120                written = self.h_write_encapsulator(len)?;
121            }
122            _ => {
123                if self.no_header {
124                    written = self.h_write_encapsulator(len)?;
125                } else {
126                    written = self.h_write_encapsulator(Length::encoded_len(len) + len + 1)?;
127                    written += self.writer.write_one(tag.inner())?;
128                    written += Length::serialize(len, &mut self.writer)?;
129                }
130            }
131        }
132        self.no_header = false; // reset state
133        Ok(written)
134    }
135
136    fn h_serialize_bytes_with_tag(&mut self, bytes: &[u8]) -> Result<usize> {
137        let mut written = self.h_write_header(self.tag_for_next_bytes, bytes.len())?;
138        written += self.writer.write_exact(bytes)?;
139
140        self.tag_for_next_bytes = Tag::OCTET_STRING; // reset to octet string
141
142        Ok(written)
143    }
144}
145
146impl<'a, 'se> serde::ser::Serializer for &'a mut Serializer<'se> {
147    type Ok = usize;
148    type Error = Asn1DerError;
149
150    type SerializeSeq = Sequence<'a, 'se>;
151    type SerializeTuple = Sequence<'a, 'se>;
152    type SerializeTupleStruct = Sequence<'a, 'se>;
153    type SerializeTupleVariant = Self;
154    type SerializeMap = Self;
155    type SerializeStruct = Sequence<'a, 'se>;
156    type SerializeStructVariant = Self;
157
158    fn is_human_readable(&self) -> bool {
159        false
160    }
161
162    fn serialize_bool(self, v: bool) -> Result<Self::Ok> {
163        debug_log!("serialize_bool: {}", v);
164        Boolean::serialize(v, self)
165    }
166
167    fn serialize_i8(self, _v: i8) -> Result<Self::Ok> {
168        debug_log!("serialize_i8: UNSUPPORTED");
169        Err(Asn1DerError::UnsupportedType)
170    }
171
172    fn serialize_i16(self, _v: i16) -> Result<Self::Ok> {
173        debug_log!("serialize_i16: UNSUPPORTED");
174        Err(Asn1DerError::UnsupportedType)
175    }
176
177    fn serialize_i32(self, _v: i32) -> Result<Self::Ok> {
178        debug_log!("serialize_i32: UNSUPPORTED");
179        Err(Asn1DerError::UnsupportedType)
180    }
181
182    fn serialize_i64(self, _v: i64) -> Result<Self::Ok> {
183        debug_log!("serialize_i64: UNSUPPORTED");
184        Err(Asn1DerError::UnsupportedType)
185    }
186
187    fn serialize_i128(self, _v: i128) -> Result<Self::Ok> {
188        debug_log!("serialize_i128: UNSUPPORTED");
189        Err(Asn1DerError::UnsupportedType)
190    }
191
192    fn serialize_u8(self, v: u8) -> Result<Self::Ok> {
193        debug_log!("serialize_u8: {}", v);
194        self.serialize_u128(v as u128)
195    }
196
197    fn serialize_u16(self, v: u16) -> Result<Self::Ok> {
198        debug_log!("serialize_u16: {}", v);
199        self.serialize_u128(v as u128)
200    }
201
202    fn serialize_u32(self, v: u32) -> Result<Self::Ok> {
203        debug_log!("serialize_u32: {}", v);
204        self.serialize_u128(v as u128)
205    }
206
207    fn serialize_u64(self, v: u64) -> Result<Self::Ok> {
208        debug_log!("serialize_u64: {}", v);
209        self.serialize_u128(v as u128)
210    }
211
212    fn serialize_u128(self, v: u128) -> Result<Self::Ok> {
213        debug_log!("serialize_u128: {}", v);
214        UnsignedInteger::serialize(v, self)
215    }
216
217    fn serialize_f32(self, _v: f32) -> Result<Self::Ok> {
218        debug_log!("serialize_f32: UNSUPPORTED");
219        Err(Asn1DerError::UnsupportedType)
220    }
221
222    fn serialize_f64(self, _v: f64) -> Result<Self::Ok> {
223        debug_log!("serialize_f64: UNSUPPORTED");
224        Err(Asn1DerError::UnsupportedType)
225    }
226
227    fn serialize_char(self, v: char) -> Result<Self::Ok> {
228        debug_log!("serialize_char: {}", v);
229        let mut buf = [0; 4];
230        self.serialize_str(v.encode_utf8(&mut buf))
231    }
232
233    fn serialize_str(self, v: &str) -> Result<Self::Ok> {
234        debug_log!("serialize_str: {}", v);
235        Utf8String::serialize(v, self)
236    }
237
238    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok> {
239        debug_log!("serialize_bytes");
240        self.h_serialize_bytes_with_tag(v)
241    }
242
243    fn serialize_none(self) -> Result<Self::Ok> {
244        debug_log!("serialize_none");
245        Ok(0)
246    }
247
248    fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Self::Ok> {
249        debug_log!("serialize_some");
250        value.serialize(self)
251    }
252
253    fn serialize_unit(self) -> Result<Self::Ok> {
254        debug_log!("serialize_unit");
255        Null::serialize(self)
256    }
257
258    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
259        debug_log!("serialize_unit_struct: {}", _name);
260        Null::serialize(self)
261    }
262
263    fn serialize_unit_variant(
264        self,
265        _name: &'static str,
266        _variant_index: u32,
267        _variant: &'static str,
268    ) -> Result<Self::Ok> {
269        debug_log!("serialize_unit_variant: UNSUPPORTED");
270        Err(Asn1DerError::UnsupportedType)
271    }
272
273    fn serialize_newtype_struct<T: ?Sized + Serialize>(self, name: &'static str, value: &T) -> Result<Self::Ok> {
274        debug_log!("serialize_newtype_struct: {}", name);
275
276        match name {
277            ObjectIdentifierAsn1::NAME => self.tag_for_next_bytes = Tag::OID,
278            BitStringAsn1::NAME => self.tag_for_next_bytes = Tag::BIT_STRING,
279            IntegerAsn1::NAME => self.tag_for_next_bytes = Tag::INTEGER,
280            UtcTimeAsn1::NAME => self.tag_for_next_bytes = Tag::UTC_TIME,
281            GeneralizedTimeAsn1::NAME => self.tag_for_next_bytes = Tag::GENERALIZED_TIME,
282            Utf8StringAsn1::NAME => self.tag_for_next_bytes = Tag::UTF8_STRING,
283            PrintableStringAsn1::NAME => self.tag_for_next_bytes = Tag::PRINTABLE_STRING,
284            NumericStringAsn1::NAME => self.tag_for_next_bytes = Tag::NUMERIC_STRING,
285            Ia5StringAsn1::NAME => self.tag_for_next_bytes = Tag::IA5_STRING,
286            BmpStringAsn1::NAME => self.tag_for_next_bytes = Tag::BMP_STRING,
287            GeneralStringAsn1::NAME => self.tag_for_next_bytes = Tag::GENERAL_STRING,
288            Asn1SetOf::<()>::NAME => self.tag_for_next_seq = Tag::SET,
289            Asn1SequenceOf::<()>::NAME => self.tag_for_next_seq = Tag::SEQUENCE,
290            BitStringAsn1Container::<()>::NAME => self.h_encapsulate(Tag::BIT_STRING),
291            OctetStringAsn1Container::<()>::NAME => self.h_encapsulate(Tag::OCTET_STRING),
292            ExplicitContextTag0::<()>::NAME => self.h_encapsulate(ExplicitContextTag0::<()>::TAG),
293            ExplicitContextTag1::<()>::NAME => self.h_encapsulate(ExplicitContextTag1::<()>::TAG),
294            ExplicitContextTag2::<()>::NAME => self.h_encapsulate(ExplicitContextTag2::<()>::TAG),
295            ExplicitContextTag3::<()>::NAME => self.h_encapsulate(ExplicitContextTag3::<()>::TAG),
296            ExplicitContextTag4::<()>::NAME => self.h_encapsulate(ExplicitContextTag4::<()>::TAG),
297            ExplicitContextTag5::<()>::NAME => self.h_encapsulate(ExplicitContextTag5::<()>::TAG),
298            ExplicitContextTag6::<()>::NAME => self.h_encapsulate(ExplicitContextTag6::<()>::TAG),
299            ExplicitContextTag7::<()>::NAME => self.h_encapsulate(ExplicitContextTag7::<()>::TAG),
300            ExplicitContextTag8::<()>::NAME => self.h_encapsulate(ExplicitContextTag8::<()>::TAG),
301            ExplicitContextTag9::<()>::NAME => self.h_encapsulate(ExplicitContextTag9::<()>::TAG),
302            ExplicitContextTag10::<()>::NAME => self.h_encapsulate(ExplicitContextTag10::<()>::TAG),
303            ExplicitContextTag11::<()>::NAME => self.h_encapsulate(ExplicitContextTag11::<()>::TAG),
304            ExplicitContextTag12::<()>::NAME => self.h_encapsulate(ExplicitContextTag12::<()>::TAG),
305            ExplicitContextTag13::<()>::NAME => self.h_encapsulate(ExplicitContextTag13::<()>::TAG),
306            ExplicitContextTag14::<()>::NAME => self.h_encapsulate(ExplicitContextTag14::<()>::TAG),
307            ExplicitContextTag15::<()>::NAME => self.h_encapsulate(ExplicitContextTag15::<()>::TAG),
308            ImplicitContextTag0::<()>::NAME => self.h_encapsulate(ImplicitContextTag0::<()>::TAG),
309            ImplicitContextTag1::<()>::NAME => self.h_encapsulate(ImplicitContextTag1::<()>::TAG),
310            ImplicitContextTag2::<()>::NAME => self.h_encapsulate(ImplicitContextTag2::<()>::TAG),
311            ImplicitContextTag3::<()>::NAME => self.h_encapsulate(ImplicitContextTag3::<()>::TAG),
312            ImplicitContextTag4::<()>::NAME => self.h_encapsulate(ImplicitContextTag4::<()>::TAG),
313            ImplicitContextTag5::<()>::NAME => self.h_encapsulate(ImplicitContextTag5::<()>::TAG),
314            ImplicitContextTag6::<()>::NAME => self.h_encapsulate(ImplicitContextTag6::<()>::TAG),
315            ImplicitContextTag7::<()>::NAME => self.h_encapsulate(ImplicitContextTag7::<()>::TAG),
316            ImplicitContextTag8::<()>::NAME => self.h_encapsulate(ImplicitContextTag8::<()>::TAG),
317            ImplicitContextTag9::<()>::NAME => self.h_encapsulate(ImplicitContextTag9::<()>::TAG),
318            ImplicitContextTag10::<()>::NAME => self.h_encapsulate(ImplicitContextTag10::<()>::TAG),
319            ImplicitContextTag11::<()>::NAME => self.h_encapsulate(ImplicitContextTag11::<()>::TAG),
320            ImplicitContextTag12::<()>::NAME => self.h_encapsulate(ImplicitContextTag12::<()>::TAG),
321            ImplicitContextTag13::<()>::NAME => self.h_encapsulate(ImplicitContextTag13::<()>::TAG),
322            ImplicitContextTag14::<()>::NAME => self.h_encapsulate(ImplicitContextTag14::<()>::TAG),
323            ImplicitContextTag15::<()>::NAME => self.h_encapsulate(ImplicitContextTag15::<()>::TAG),
324            HeaderOnly::<()>::NAME => self.no_header = true,
325            Asn1RawDer::NAME => self.no_header = true,
326            _ => {}
327        }
328
329        value.serialize(self)
330    }
331
332    fn serialize_newtype_variant<T: ?Sized + Serialize>(
333        self,
334        _name: &'static str,
335        _variant_index: u32,
336        _variant: &'static str,
337        _value: &T,
338    ) -> Result<Self::Ok> {
339        debug_log!("serialize_newtype_variant: UNSUPPORTED");
340        Err(Asn1DerError::UnsupportedType)
341    }
342
343    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
344        debug_log!("serialize_seq");
345        let mut tag = Tag::SEQUENCE;
346        std::mem::swap(&mut tag, &mut self.tag_for_next_seq);
347        Ok(Sequence::serialize_lazy(self, tag))
348    }
349
350    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
351        debug_log!("serialize_tuple: {}", len);
352        self.serialize_seq(Some(len))
353    }
354
355    fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeTupleStruct> {
356        debug_log!("serialize_tuple_struct: {}({})", _name, len);
357        self.serialize_seq(Some(len))
358    }
359
360    fn serialize_tuple_variant(
361        self,
362        _name: &'static str,
363        _variant_index: u32,
364        _variant: &'static str,
365        _len: usize,
366    ) -> Result<Self::SerializeTupleVariant> {
367        debug_log!("serialize_tuple_variant: UNSUPPORTED");
368        Err(Asn1DerError::UnsupportedType)
369    }
370
371    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
372        debug_log!("serialize_map: UNSUPPORTED");
373        Err(Asn1DerError::UnsupportedType)
374    }
375
376    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
377        debug_log!("serialize_struct: {}", _name);
378        self.serialize_seq(Some(len))
379    }
380
381    fn serialize_struct_variant(
382        self,
383        _name: &'static str,
384        _variant_index: u32,
385        _variant: &'static str,
386        _len: usize,
387    ) -> Result<Self::SerializeStructVariant> {
388        debug_log!("serialize_struct_variant: UNSUPPORTED");
389        Err(Asn1DerError::UnsupportedType)
390    }
391}
392
393impl serde::ser::SerializeTupleVariant for &mut Serializer<'_> {
394    type Ok = usize;
395    type Error = Asn1DerError;
396
397    fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<()> {
398        unimplemented!("The implementation does not support tuple variants")
399    }
400
401    fn end(self) -> Result<Self::Ok> {
402        unimplemented!("The implementation does not support tuple variants")
403    }
404}
405
406impl serde::ser::SerializeMap for &mut Serializer<'_> {
407    type Ok = usize;
408    type Error = Asn1DerError;
409
410    fn serialize_key<T: ?Sized + Serialize>(&mut self, _key: &T) -> Result<()> {
411        unimplemented!("The implementation does not support maps")
412    }
413
414    fn serialize_value<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<()> {
415        unimplemented!("The implementation does not support maps")
416    }
417
418    fn end(self) -> Result<Self::Ok> {
419        unimplemented!("The implementation does not support maps")
420    }
421}
422
423impl serde::ser::SerializeStructVariant for &mut Serializer<'_> {
424    type Ok = usize;
425    type Error = Asn1DerError;
426
427    fn serialize_field<T: ?Sized + Serialize>(&mut self, _key: &'static str, _value: &T) -> Result<()> {
428        unimplemented!("The implementation does not support struct variants")
429    }
430
431    fn end(self) -> Result<Self::Ok> {
432        unimplemented!("The implementation does not support struct variants")
433    }
434}