CommunityToolkit / CommunityToolkit/dotnet

SpanBuilder

Open
#368 5 comments 0 reactions 0 assignees View on GitHub
feature request :mailbox_with_mail: high-performance 🚂
Dominant language
C#
Stars
3.8k
Forks
400
PR merge metrics
No merged PRs in 30d

Description

### Overview

A `StringBuilder`-like api, but for spans.

### API breakdown

```cs
public ref struct SpanBuilder
{
Span span;
int length;

public SpanBuilder(Span storage) { span = storage; }
public SpanBuilder(int capacity) { span = new T[capacity]; }

public void Add(in T @value)
{
EnsureCapacity(length + 1);
span[length++] = @value;
}
public EnsureCapacity(int capacity)
{
if(span.Length >= capacity) return;
Span newSpan = new T[Math.Pow(2, BitOperations.LeadingZeroCount(checked((uint)capacity)))];
span.Slice(0, length).CopyTo(newSpan);
span = newSpan;
}
public Span Build(){
Span built = span.Slice(0, length);
span = default;
length = default;
return built;
}
}
```

### Usage example

// too big 😅

### Breaking change?

No

### Alternatives

# `List`

- causes allocation by itself (isn't a value type)
- doesn't support use of existing storage

# StringBuilder

- only for strings

# ValueStringBuilder

- is internal

### Additional context

_No response_

### Help us help you

Yes, I'd like to be assigned to work on this item

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.