Skip to content

Add MaxDepth property to CborReader #128087

@bartonjs

Description

@bartonjs

Background and motivation

CBOR is structured like JSON, meaning that skipping over an array or map requires processing all of the elements within that array or map to find where the container ends. This means that a deeply nested array-or-map can use a surprising amount of memory on a skip operation.

Also, deeply nested data is always risky for recursive algorithms.

API Proposal

  • A new default maxDepth parameter to the ctor.
  • A new ctor that has no defaults (per the more-than-2-defaults guideline)
  • A new MaxDepth property
namespace System.Formats.Cbor
{
    public partial class CborReader
    {
        public CborReader(System.ReadOnlyMemory<byte> data);
        public CborReader(System.ReadOnlyMemory<byte> data, System.Formats.Cbor.CborConformanceMode conformanceMode = System.Formats.Cbor.CborConformanceMode.Strict, bool allowMultipleRootLevelValues = false, int maxDepth = 0);
    }
}

And hide the existing ctor with defaults:

namespace System.Formats.Cbor
{
    public partial class CborReader
    {
+       [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
        public CborReader(System.ReadOnlyMemory<byte> data, System.Formats.Cbor.CborConformanceMode conformanceMode, bool allowMultipleRootLevelValues) { }
    }
}

API Usage

var reader = new CborReader({ 0x81, 0x81, 0x00 }, maxDepth: 1);

reader.ReadStartArray();

// throws, too deep
reader.ReadStartArray();

Alternative Designs

Decide that 3 options is enough to warrant an options type:

namespace System.Formats.Cbor
{
    public struct CborReaderOptions
    {
        public bool AllowMultipleRootLevelValues { get; set; }
        public CborConformanceMode ConformanceMode { get; set; }
        public int MaxDepth { get; set; }
    }

    public partial class CborReader
    {
        public CborReader(System.ReadOnlyMemory<byte> data, CborReaderOptions options);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions