-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterpolatedStringFormatter.cs
92 lines (80 loc) · 2.72 KB
/
InterpolatedStringFormatter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace InterpolatedStringFormatter
{
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;
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();
}
}
}