Skip to content
This repository was archived by the owner on Aug 2, 2023. It is now read-only.
This repository was archived by the owner on Aug 2, 2023. It is now read-only.

Suggestion: Span/ReadOnlySpan / Utf8String operators for ArraySegment<T> #832

@mgravell

Description

@mgravell

There are already operators:

    public static implicit operator ReadOnlySpan<T>(T[] array);
    public static implicit operator Span<T>(T[] array);

Use case: have loaded data over a network and split (parsed) the data into tokens that you want to expose upstream with zero copies; have class:

public class Customer {
    public Utf8String Name {get;}
    public Utf8String Address {get;}
}

Here we can't store a Span<T> or a Utf8String directly as fields because of the stack-only semantics; but we could store the array-segments:

public class Customer {
    private ArraySegment<byte> _name, _address;
    public Utf8String Name => new Utf8String(new ReadOnlySpan<byte>(_name.Array, _name.Offset, _name.Count));
    public Utf8String Address => new Utf8String(new ReadOnlySpan<byte>(_address.Array, _address.Offset, _address.Count));
}

With the addition of:

    public static implicit operator ReadOnlySpan<T>(ArraySegment<T> segment);
    public static implicit operator Span<T>(ArraySegment<T> segment);

this becomes much more convenient:

public class Customer {
    private ArraySegment<byte> _name, _address;
    public Utf8String Name => new Utf8String(_name);
    public Utf8String Address => new Utf8String(_address);
}

This pairs quite nicely with the TryGetArrayElseGetPointer method which already exposes ArraySegment<byte> as part of the API surface.


Although it also prompts the question: should Utf8String also have operators for this type of scenario, for example:

public class Customer {
    private ArraySegment<byte> _name, _address;
    public Utf8String Name => _name;
    public Utf8String Address => _address;
}

via:

public static implicit operator Utf8String(ArraySegment<byte> segment);

That might be a step too far, though.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions