Skip to content

Commit 8db0c90

Browse files
authored
Provide lengths for all types (#558)
1 parent 8b22c71 commit 8db0c90

File tree

2 files changed

+19
-7
lines changed

2 files changed

+19
-7
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ $ cargo add asn1 --no-default-features
2929

3030
- Added `Asn1Writable::encoded_length`, `SimpleAsn1Writable::data_length`, and
3131
`Asn1DefinedByWritable::encoded_length`. Implementing these functions reduces
32-
the number of re-allocations required when writing.
32+
the number of re-allocations required when writing. `None` can be returned if
33+
it is not possible to provide an efficient implementation.
3334

3435
#### Changes
3536

src/types.rs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -96,12 +96,10 @@ pub trait SimpleAsn1Writable: Sized {
9696
/// Get the length of the data content (without tag and length bytes) if it
9797
/// can be calculated efficiently.
9898
///
99-
/// The default implementation returns None, meaning the length is unknown.
100-
/// Providing this method reduces the number of re-allocations required in
101-
/// writing.
102-
fn data_length(&self) -> Option<usize> {
103-
None
104-
}
99+
/// It is always safe to return `None`, which indicates the length is
100+
/// unknown. Returning `Some(...)` from this method reduces the number of
101+
/// re-allocations required in writing.
102+
fn data_length(&self) -> Option<usize>;
105103
}
106104

107105
/// A trait for types that can be parsed based on a `DEFINED BY` value.
@@ -1608,6 +1606,10 @@ impl SimpleAsn1Writable for SequenceWriter<'_> {
16081606
fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
16091607
(self.f)(&mut Writer::new(dest))
16101608
}
1609+
1610+
fn data_length(&self) -> Option<usize> {
1611+
None
1612+
}
16111613
}
16121614

16131615
/// Represents an ASN.1 `SEQUENCE OF`. This is an `Iterator` over values that
@@ -1753,6 +1755,11 @@ impl<
17531755

17541756
Ok(())
17551757
}
1758+
1759+
fn data_length(&self) -> Option<usize> {
1760+
let iter = self.clone();
1761+
iter.map(|el| el.encoded_length()).sum()
1762+
}
17561763
}
17571764

17581765
/// Writes a `SEQUENCE OF` ASN.1 structure from a slice of `T`.
@@ -1898,6 +1905,10 @@ impl<'a, T: Asn1Readable<'a> + Asn1Writable> SimpleAsn1Writable for SetOf<'a, T>
18981905

18991906
Ok(())
19001907
}
1908+
fn data_length(&self) -> Option<usize> {
1909+
let iter = self.clone();
1910+
iter.map(|el| el.encoded_length()).sum()
1911+
}
19011912
}
19021913

19031914
/// Writes an ASN.1 `SET OF` whose contents is a slice of `T`. This type handles

0 commit comments

Comments
 (0)