Skip to content

[API Proposal]: IDataTransformation<TInput, TOutput> Interface #122358

Closed as not planned

Description

@deniszykov

Background and motivation

The .NET Base Class Library contains numerous data transformation algorithms that share remarkably similar patterns but lack a common interface. These include:

  • Encoders/Decoders: Base64, Utf8Encoder, AsciiEncoder
  • Compression: BrotliEncoder, BrotliDecoder, DeflateStream
  • Cryptography: Various encryption/decryption transformers, hash transformers etc.

All these types share:

  • Similar method signatures using ReadOnlySpan<T> and Span<T>
  • The same OperationStatus return type
  • Identical patterns for handling partial data (inputConsumed, outputWritten)
  • Common concerns around buffer management and streaming scenarios

However, the lack of a unified interface creates several problems:

  1. No generic programming support: Cannot write reusable code that works with any transformation algorithm
  2. Code duplication: Developers must write similar buffer management logic for each transformer type
  3. Limited composability: Cannot easily chain or wrap transformers generically
  4. Testing complexity: Difficult to create mock implementations or test harnesses that work across different transformation types
  5. Discoverability: New developers may not recognize the common pattern across these APIs

Real-World Use Cases

  1. Pipeline Processing: Building data processing pipelines where transformation steps can be configured at runtime (e.g., decompress → decrypt → decode)
  2. Stream Adapters: Creating generic Stream wrappers that apply any transformation (eg. TransformStream similar to CryptoStream)
  3. Buffering Libraries: Writing reusable buffer management code that works with any transformer.

API Proposal

namespace System.Buffers
{
    /// <summary>
    /// Provides a standard contract for data transformation algorithms such as encoding/decoding,
    /// compression/decompression, and encryption/decryption.
    /// </summary>
    /// <typeparam name="TInput">The type of elements in the input data.</typeparam>
    /// <typeparam name="TOutput">The type of elements in the output data.</typeparam>
    public interface IDataTransformation<TInput, TOutput>
    {
        /// <summary>
        /// Transforms a block of input data and stores the result in the output buffer.
        /// </summary>
        /// <param name="input">The source data to transform.</param>
        /// <param name="output">The destination buffer for transformed data.</param>
        /// <param name="inputConsumed">The number of input elements consumed during transformation.</param>
        /// <param name="outputWritten">The number of output elements written during transformation.</param>
        /// <param name="options">Options controlling the transformation behavior.</param>
        /// <returns>
        /// The status of the transformation operation:
        /// <list type="bullet">
        /// <item><description><see cref="OperationStatus.Done"/>: Transformation completed successfully for this block.</description></item>
        /// <item><description><see cref="OperationStatus.DestinationTooSmall"/>: Output buffer is too small to continue.</description></item>
        /// <item><description><see cref="OperationStatus.NeedMoreData"/>: More input data is required to continue.</description></item>
        /// <item><description><see cref="OperationStatus.InvalidData"/>: Input data is invalid and transformation cannot continue.</description></item>
        /// </list>
        /// </returns>
        OperationStatus Transform(
            ReadOnlySpan<TInput> input, 
            Span<TOutput> output, 
            out int inputConsumed, 
            out int outputWritten, 
            TransformOptions options);
    }

    /// <summary>
    /// Specifies options for data transformation operations.
    /// </summary>
    [Flags]
    public enum TransformOptions
    {
        /// <summary>
        /// No special options.
        /// </summary>
        None = 0,

        /// <summary>
        /// Indicates this is the first block of data in a transformation sequence.
        /// Implementations may use this to initialize state or write headers.
        /// </summary>
        Starting = 0x1 << 1,

        /// <summary>
        /// Indicates this is the final block of data in a transformation sequence.
        /// Implementations should finalize the transformation and flush any remaining data.
        /// </summary>
        Final = 0x1 << 2,

        /// <summary>
        /// For block-based algorithms, continues transformation beyond natural block boundaries
        /// without returning <see cref="OperationStatus.Done"/> at block endings i.e. process as many blocks as possible. Without this flag, the algorithm will only process one block.
        /// </summary>
        Exhausting = 0x1 << 3,
    }
}

API Usage

public class TransformStream<TTransform> : Stream
    where TTransform : IDataTransformation<byte, byte>
{
    private readonly Stream _inner;
    private readonly TTransform _transformer;
    private readonly byte[] _buffer = new byte[8192];
    
    public TransformStream(Stream inner, TTransform transformer)
    {
        _inner = inner;
        _transformer = transformer;
    }
    
    public override int Read(Span<byte> buffer)
    {
        int bytesRead = _inner.Read(_buffer);
        var options = TransformOptions.None;
        if (bytesRead < _buffer.Length)
            options |= TransformOptions.Final;
            
        _transformer.Transform( 
            _buffer.AsSpan(0, bytesRead),
            buffer,
            out _,  // This is a naive approach, suitable only for example.
            out int written,
            options);
            
        return written;
    }
    
    // Other Stream members...
}

// Usage: Read compressed data transparently
using var compressed = File.OpenRead("data.br");
using var decompressed = new TransformStream<BrotliDecoder>(compressed, new BrotliDecoder());

Alternative Designs

Alternative 1: Separate Encode/Decode Interfaces

Instead of a single generic interface, provide separate IEncoder<TInput, TOutput> and IDecoder<TInput, TOutput> interfaces.

Pros:

  • More semantic clarity about direction of transformation
  • Could have different method signatures optimized for each direction

Cons:

  • Many transformers are bidirectional and would need to implement both
  • Increases API surface area
  • The underlying pattern is identical, so separation may not add value

Alternative 2: No Options Parameter

Remove TransformOptions and use only one isFinal parameter, etc.

Pros:

  • Simpler method signature
  • More explicit about operation mode

Cons:

  • Existing APIs use the options pattern successfully
  • Flags provide flexibility for future extensions

Risks

1. Performance Overhead

Risk: Interface dispatch might introduce virtual call overhead compared to direct method calls.

Mitigation:

  • Modern JIT compilers optimize interface calls well, especially with generics
  • For performance-critical code, users can continue calling concrete types directly
  • The benefit of generic code often outweighs minor performance costs
  • Using structs for encoder/decoder types and generics could negate any performance impact from virtual calls.

2. Incomplete Abstraction

Risk: The interface may not capture all nuances of different transformation types (stateful vs stateless, initialization requirements, error handling, etc.).

Mitigation:

  • The interface captures the common pattern shared by existing APIs
  • Implementation-specific features remain on concrete types
  • This is a lowest-common-denominator interface by design
  • Advanced scenarios can use concrete types directly

3. API Evolution Challenges

Risk: Future needs might require interface changes, which would be breaking.

Mitigation:

  • The design is based on proven patterns from existing stable APIs and inspired by the gzip library, which is already 30 years old.
  • TransformOptions enum is flags-based and extensible

4. Generic Constraints Limitations

Risk: TInput and TOutput being unbounded might allow nonsensical combinations.

Mitigation:

  • Could add where TInput : unmanaged where TOutput : unmanaged but this might be too restrictive

4. Adoption Complexity

Risk: Retrofitting existing types to implement this interface could require work and testing.

Mitigation:

  • Implementation can be phased, starting with interface only.
  • Existing types already follow this pattern; implementation would be mostly adding the interface declaration
  • Extensive testing infrastructure already exists for these types
  • Community feedback during preview phases can identify issues

Activity

  1. added
    api-suggestion
    on Dec 9, 2025
  2. added
    untriaged
    on Dec 9, 2025
  3. added
    needs-area-label
    on Dec 9, 2025
  4. changed the title [-][API Proposal]:[/-] [+][API Proposal]: IDataTransformation<TInput, TOutput> Interface[/+] on Dec 9, 2025
  5. deniszykov commented on Dec 10, 2025

    @deniszykov
    Author

    Here are a few implementations that I have found useful in my work.:

  6. added and removed
    needs-area-label
    on Dec 10, 2025
  7. tannergooding commented on Jul 11, 2026

    @tannergooding
    Member

    This is too broad/general of an API without a clear use case. Its not something we're interested in providing at this time

  8. removed
    untriaged
    on Jul 11, 2026
  9. locked and limited conversation to collaborators on Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions