KEMBAR78
[API Proposal]: InitialCapacity for AsnWriter · Issue #69573 · dotnet/runtime · GitHub
Skip to content

[API Proposal]: InitialCapacity for AsnWriter #69573

@vcsjones

Description

@vcsjones

Background and motivation

There are many places throughout the Libraries where we use AsnWriter for little writes. Consider X509KeyUsageExtension's managed implementation:

AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
writer.WriteNamedBitList(keyUsagesAsn);
return writer.Encode();

In this case, the total encoded size of the extension is going to be at most 5 bytes.

However, right off the bat, the AsnWriter starts off with a buffer of 1024 bytes.

So that's 1019 bytes that we really almost never end up using.

This similar line of thought applies to

  1. Encoding basic constraints:

    AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
    constraints.Encode(writer);
    return writer.Encode();

  2. Encoding extended key usages. This one is a little less of a perfect example, but the majority of certificates that get encoded have serverAuth and clientAuth, which encode to a compact 22 bytes.

  3. Converting IEEE1363 signatures to DER form, we can give a reasonable hint.

  4. On the flip side, there may be places we want to specify a larger capacity by default, such as the managed PKCS12 implementation.

The initialCapacity would just be a hint for the first internally allocated buffer. If the ends up needing to re-allocate+copy, the current behavior would continue.

API Proposal

namespace System.Formats.Asn1;

public sealed partial class AsnWriter {
+    public AsnWriter(AsnEncodingRules ruleSet, int initialCapacity);
}

API Usage

AsnWriter writer = new AsnWriter(AsnEncodingRules.DER, initialCapacity: 5);
writer.WriteNamedBitList(keyUsagesAsn);
byte[] encoded = writer.Encode();

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions