Skip to content

Commit e30c679

Browse files
daxpeddadishmaker
andauthored
der: fix append in Encode::encode_to_vec (#1760) (#1765)
* der: fix append in `Encode::encode_to_vec` * der: test encode_to_vec with append Co-authored-by: dishmaker <[email protected]>
1 parent a4ad7d0 commit e30c679

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

der/src/encode.rs

+5-6
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

+23-1
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ mod sequence {
226226
// ```
227227
//
228228
// [RFC 5280 Section 5.2.5]: https://datatracker.ietf.org/doc/html/rfc5280#section-5.2.5
229-
#[derive(Sequence)]
229+
#[derive(Sequence, Default)]
230230
pub struct IssuingDistributionPointExample {
231231
// Omit distributionPoint and only_some_reasons because corresponding structs are not
232232
// available here and are not germane to the example
@@ -408,6 +408,28 @@ mod sequence {
408408
assert_eq!(idp.only_contains_attribute_certs, true);
409409
}
410410

411+
#[test]
412+
fn idp_encode_twice() {
413+
let mut vec_buf = Vec::new();
414+
415+
IssuingDistributionPointExample {
416+
only_contains_user_certs: true,
417+
..Default::default()
418+
}
419+
.encode_to_vec(&mut vec_buf)
420+
.unwrap();
421+
422+
// encode to the same vec by appending
423+
IssuingDistributionPointExample {
424+
only_contains_cacerts: true,
425+
..Default::default()
426+
}
427+
.encode_to_vec(&mut vec_buf)
428+
.unwrap();
429+
430+
assert_eq!(vec_buf, hex!("30038101FF 30038201FF"));
431+
}
432+
411433
// demonstrates default field that is not context specific
412434
#[test]
413435
fn extension_test() {

0 commit comments

Comments
 (0)