Skip to content

Commit f66f4c5

Browse files
authored
der: fix append in Encode::encode_to_vec (#1760)
* der: fix append in `Encode::encode_to_vec` * der: test encode_to_vec with append
1 parent c76165b commit f66f4c5

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

der/src/encode.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use crate::{Header, Length, Result, SliceWriter, Tagged, Writer};
44
use core::marker::PhantomData;
55

66
#[cfg(feature = "alloc")]
7-
use {alloc::boxed::Box, alloc::vec::Vec, core::iter};
7+
use {alloc::boxed::Box, alloc::vec::Vec};
88

99
#[cfg(feature = "pem")]
1010
use {
@@ -40,12 +40,11 @@ pub trait Encode {
4040
#[cfg(feature = "alloc")]
4141
fn encode_to_vec(&self, buf: &mut Vec<u8>) -> Result<Length> {
4242
let expected_len = usize::try_from(self.encoded_len()?)?;
43-
buf.reserve(expected_len);
44-
buf.extend(iter::repeat(0).take(expected_len));
43+
let initial_len = buf.len();
44+
buf.resize(initial_len + expected_len, 0u8);
4545

46-
let mut writer = SliceWriter::new(buf);
47-
self.encode(&mut writer)?;
48-
let actual_len = writer.finish()?.len();
46+
let buf_slice = &mut buf[initial_len..];
47+
let actual_len = self.encode_to_slice(buf_slice)?.len();
4948

5049
if expected_len != actual_len {
5150
return Err(ErrorKind::Incomplete {

der/tests/derive.rs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ mod sequence {
271271
// ```
272272
//
273273
// [RFC 5280 Section 5.2.5]: https://datatracker.ietf.org/doc/html/rfc5280#section-5.2.5
274-
#[derive(Sequence)]
274+
#[derive(Sequence, Default)]
275275
pub struct IssuingDistributionPointExample {
276276
// Omit distributionPoint and only_some_reasons because corresponding structs are not
277277
// available here and are not germane to the example
@@ -601,6 +601,28 @@ mod sequence {
601601
assert_eq!(idp.only_contains_attribute_certs, true);
602602
}
603603

604+
#[test]
605+
fn idp_encode_twice() {
606+
let mut vec_buf = Vec::new();
607+
608+
IssuingDistributionPointExample {
609+
only_contains_user_certs: true,
610+
..Default::default()
611+
}
612+
.encode_to_vec(&mut vec_buf)
613+
.unwrap();
614+
615+
// encode to the same vec by appending
616+
IssuingDistributionPointExample {
617+
only_contains_cacerts: true,
618+
..Default::default()
619+
}
620+
.encode_to_vec(&mut vec_buf)
621+
.unwrap();
622+
623+
assert_eq!(vec_buf, hex!("30038101FF 30038201FF"));
624+
}
625+
604626
// demonstrates default field that is not context specific
605627
#[test]
606628
fn extension_test() {

0 commit comments

Comments
 (0)