Home

Awesome

Logo Nemesis.TextParsers

Build status - main Tests Last commit Last release

Code size Issues Commit activity GitHub stars

Nuget Downloads

Nuget Downloads

Nuget Downloads

License FOSSA Status


Benefits and Features

TL;DR - are you looking for performant, non allocating serializer from structural object to flat, human editable string? Look no further. Benchmarks shows potential gains from using Nemesis.TextParsers

MethodCountMeanRatioAllocated
TextJson10121.02 us1.0035200 B
TextJsonBytes10120.79 us1.0030400 B
TextJsonNet10137.28 us1.13288000 B
TextParsers1049.02 us0.416400 B
TextJson100846.06 us1.00195200 B
TextJsonBytes100845.84 us1.00163200 B
TextJsonNet100943.71 us1.12636800 B
TextParsers100463.33 us0.5542400 B
TextJson10008,142.13 us1.001639200 B
TextJsonBytes10008,155.41 us1.001247200 B
TextJsonNet10008,708.12 us1.073880800 B
TextParsers10004,384.00 us0.54402400 B

More comprehensive examples are here

Other popular choices

When stucked with a task of parsing various items form strings we often opt for TypeConverter. We tend to create methods like:

public static T FromString<T>(string text) =>
    (T)TypeDescriptor.GetConverter(typeof(T))
        .ConvertFromInvariantString(text);

or even create similar constructs to be in line with object oriented design:

public abstract class TextTypeConverter : TypeConverter
{
    public sealed override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) =>
        sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);

    public sealed override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) =>
        destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
}

public abstract class BaseTextConverter<TValue> : TextTypeConverter
{
    public sealed override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) =>
        value is string text ? ParseString(text) : default;

    public abstract TValue ParseString(string text);
    

    public sealed override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) =>
        destinationType == typeof(string) ?
            FormatToString((TValue)value) :
            base.ConvertTo(context, culture, value, destinationType);

    public abstract string FormatToString(TValue value);
}

What is wrong with that? Well, nothing... except of performance and possibly - support for generics.

TypeConverter was designed around 2002 when processing power tended to double every now and then and (in my opinion) it was more suited for creating GUI-like editors where performance usually is not an issue. But imagine a service application like exchange trading suite that has to perform multiple operations per second and in such cases processor has more important thing to do than parsing strings.

Features

  1. as concise as possible - both JSON or XML exist but they are not ready to be created from hand by human support
  2. works in various architectures supporting .Net Core and .Net Standard and is culture independent
  3. support for basic system types (C#-like type names):
    • string
    • bool
    • byte/sbyte, short/ushort, int/uint, long/ulong
    • float/double
    • decimal
    • BigInteger
    • TimeSpan, DateTime/DateTimeOffset
    • Guid, Uri
  4. supports pattern based parsing/formatting via ToString/FromText methods placed inside type or static/instance factory
  5. supports compound types:
    • KeyValuePair<,> and ValueTuple of any arity
    • Enums (with underlying number types; code gen and reflection based)
    • Nullables
    • Dictionaries (built-in i.e. SortedDictionary/SortedList and custom ones)
    • Arrays (including jagged arrays)
    • Standard collections and collection contracts (List vs IList vs IEnumerable)
    • User defined collections
    • everything mentioned above but combined with inner elements properly escaped in final string i.e. SortedDictionary<char?, IList<float[][]>>
  6. ability to fallback to TypeConverter if no parsing/formatting strategy was found
  7. parsing is fast to while allocating as little memory as possible upon parsing. The following benchmark illustrates this speed via parsing 1000 element array
MethodMeanRatioGen 0Gen 1AllocatedRemarks
RegEx parsing4,528.99 us44.98492.1875-2089896 BRegular expression with escaping support
StringSplitTest_KnownType93.41 us0.929.52150.122140032 Bstring.Split(..).Select(text=>int.Parse(text))
StringSplitTest_DynamicType474.73 us4.6924.4141-104032 Bstring.Split + TypeDescriptor.GetConverter
SpanSplitTest_NoAlloc101.00 us1.00---"1|2|3".AsSpan().Tokenize()
SpanSplitTest_Alloc101.38 us1.000.8545-4024 B"1|2|3".AsSpan().Tokenize(); var array = new int[1000];
  1. provides basic building blocks for parser's callers to be able to create their own transformers/factories
    • LeanCollection that can store 1,2,3 or more elements
    • SpanSplit - string.Split equivalent is provided to accept faster representation of string - ReadOnlySpan<char>. Supports both standard and custom escaping sequences
    • access to every implemented parser/formatter
  2. basic LINQ support
var avg = "1|2|3".AsSpan()
    .Tokenize('|', '\\', true)
    .Parse('\\', '∅', '|')
    .Average(DoubleTransformer.Instance);
  1. basic support for GUI editors for compound types like collections/dictionaries: CollectionMeta, DictionaryMeta
  2. lean/frugal implementation of StringBuilder - ValueSequenceBuilder
Span<char> initialBuffer = stackalloc char[32];
using var accumulator = new ValueSequenceBuilder<char>initialBuffer);
using (var enumerator = coll.GetEnumerator())
    while (enumerator.MoveNext())
        FormatElement(formatter, enumerator.Current, ref accumulator);
return accumulator.AsSpanTo(accumulator.Length > 0 ? accumulator.Length - 1 : 0).ToString();
  1. usage of C# 9.0 code-gen (and Incremental Code Generators) to provide several transformers for common cases where parsing logic is straightforward

Road map

Links

Funding

Open source software is free to use but creating and maintaining is a laborious effort. Should you wish to support us in our noble endeavour, please consider the following donation methods: Donate using Liberapay Liberapay receiving

If you just want to say thanks, you can buy me a ☕ or ⭐ any of my repositories.

License

FOSSA Status