Created
October 15, 2022 15:19
-
-
Save OFark/40cbbe80f71df93bb2e32dca38a0fbfc to your computer and use it in GitHub Desktop.
Interpolated String Formatter
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
var url = new InterpolatedStringFormatter("/api/{product}/order", productName).ToString(); |
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 readonly struct InterpolatedStringFormatter : IReadOnlyList<KeyValuePair<string, object>> | |
{ | |
internal const int MaxCachedFormatters = 1024; | |
private const string NullFormat = "[null]"; | |
private static int _count; | |
private static ConcurrentDictionary<string, StringValuesFormatter> _formatters = new ConcurrentDictionary<string, StringValuesFormatter>(); | |
private readonly StringValuesFormatter _formatter; | |
private readonly object[] _values; | |
private readonly string _originalMessage; | |
// for testing purposes | |
internal StringValuesFormatter Formatter => _formatter; | |
public InterpolatedStringFormatter(string format, params object[] values) | |
{ | |
if (values != null && values.Length != 0 && format != null) | |
{ | |
if (_count >= MaxCachedFormatters) | |
{ | |
if (!_formatters.TryGetValue(format, out _formatter)) | |
_formatter = new StringValuesFormatter(format); | |
} | |
else | |
{ | |
_formatter = _formatters.GetOrAdd(format, f => | |
{ | |
Interlocked.Increment(ref _count); | |
return new StringValuesFormatter(f); | |
}); | |
} | |
} | |
else | |
{ | |
_formatter = null; | |
} | |
_originalMessage = format ?? NullFormat; | |
_values = values; | |
} | |
public KeyValuePair<string, object> this[int index] { | |
get { | |
if (index < 0 || index >= Count) | |
throw new IndexOutOfRangeException(nameof(index)); | |
if (index == Count - 1) | |
return new KeyValuePair<string, object>("{OriginalFormat}", _originalMessage); | |
return _formatter.GetValue(_values, index); | |
} | |
} | |
public int Count { | |
get { | |
if (_formatter == null) | |
return 1; | |
return _formatter.ValueNames.Count + 1; | |
} | |
} | |
public IEnumerator<KeyValuePair<string, object>> GetEnumerator() | |
{ | |
for (var i = 0; i < Count; ++i) | |
{ | |
yield return this[i]; | |
} | |
} | |
public override string ToString() | |
{ | |
if (_formatter == null) | |
return _originalMessage; | |
return _formatter.Format(_values); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment