Created
September 3, 2019 19:20
-
-
Save DevJohnC/402c71fb5f8363fa7ca4d813c311e263 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ref struct ParsedString | |
{ | |
private readonly ReadOnlySpan<byte> _valueSpan; | |
private readonly Encoding _encoding; | |
private readonly string _value; | |
public bool IsDeferred { get; } | |
/// <summary> | |
/// Deferred reading ctor. | |
/// </summary> | |
/// <param name="valueSpan"></param> | |
/// <param name="encoding"></param> | |
public ParsedString(ReadOnlySpan<byte> valueSpan, Encoding encoding) | |
{ | |
_valueSpan = valueSpan; | |
_encoding = encoding; | |
_value = default; | |
IsDeferred = true; | |
} | |
/// <summary> | |
/// Non-deferred reading ctor. | |
/// </summary> | |
/// <param name="value"></param> | |
public ParsedString(string value) | |
{ | |
_valueSpan = default; | |
_encoding = default; | |
_value = value; | |
IsDeferred = false; | |
} | |
public string GetString() | |
{ | |
if (!IsDeferred) | |
return _value; | |
if (_valueSpan.IsEmpty) | |
return string.Empty; | |
unsafe | |
{ | |
fixed (byte* ptr = _valueSpan) | |
{ | |
return _encoding.GetString(ptr, _valueSpan.Length); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment