-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ValueFormatter.cs
362 lines (327 loc) · 14.7 KB
/
ValueFormatter.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//
// Copyright (c) 2004-2019 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using NLog.Config;
using NLog.Internal;
namespace NLog.MessageTemplates
{
/// <summary>
/// Convert Render or serialize a value, with optionally backwards-compatible with <see cref="string.Format(System.IFormatProvider,string,object[])"/>
/// </summary>
internal class ValueFormatter : IValueFormatter
{
public static IValueFormatter Instance
{
get => _instance ?? (_instance = new ValueFormatter());
set => _instance = value ?? new ValueFormatter();
}
private static IValueFormatter _instance;
private static readonly IEqualityComparer<object> _referenceEqualsComparer = SingleItemOptimizedHashSet<object>.ReferenceEqualityComparer.Default;
/// <summary>Singleton</summary>
private ValueFormatter()
{
}
private const int MaxRecursionDepth = 2;
private const int MaxValueLength = 512 * 1024;
private const string LiteralFormatSymbol = "l";
private readonly MruCache<Enum, string> _enumCache = new MruCache<Enum, string>(1500);
public const string FormatAsJson = "@";
public const string FormatAsString = "$";
/// <summary>
/// Serialization of an object, e.g. JSON and append to <paramref name="builder"/>
/// </summary>
/// <param name="value">The object to serialize to string.</param>
/// <param name="format">Parameter Format</param>
/// <param name="captureType">Parameter CaptureType</param>
/// <param name="formatProvider">An object that supplies culture-specific formatting information.</param>
/// <param name="builder">Output destination.</param>
/// <returns>Serialize succeeded (true/false)</returns>
public bool FormatValue(object value, string format, CaptureType captureType, IFormatProvider formatProvider, StringBuilder builder)
{
switch (captureType)
{
case CaptureType.Serialize:
{
return ConfigurationItemFactory.Default.JsonConverter.SerializeObject(value, builder);
}
case CaptureType.Stringify:
{
builder.Append('"');
FormatToString(value, null, formatProvider, builder);
builder.Append('"');
return true;
}
default:
{
return FormatObject(value, format, formatProvider, builder);
}
}
}
/// <summary>
/// Format an object to a readable string, or if it's an object, serialize
/// </summary>
/// <param name="value">The value to convert</param>
/// <param name="format"></param>
/// <param name="formatProvider"></param>
/// <param name="builder"></param>
/// <returns></returns>
public bool FormatObject(object value, string format, IFormatProvider formatProvider, StringBuilder builder)
{
if (SerializeSimpleObject(value, format, formatProvider, builder, false))
{
return true;
}
IEnumerable collection = value as IEnumerable;
if (collection != null)
{
return SerializeWithoutCyclicLoop(collection, format, formatProvider, builder, default(SingleItemOptimizedHashSet<object>), 0);
}
SerializeConvertToString(value, formatProvider, builder);
return true;
}
/// <summary>
/// Try serialising a scalar (string, int, NULL) or simple type (IFormattable)
/// </summary>
private bool SerializeSimpleObject(object value, string format, IFormatProvider formatProvider, StringBuilder builder, bool convertToString = true)
{
if (value is string stringValue)
{
SerializeStringObject(stringValue, format, builder);
return true;
}
if (value == null)
{
builder.Append("NULL");
return true;
}
// Optimize for types that are pretty much invariant in all cultures when no format-string
if (value is IConvertible convertibleValue)
{
SerializeConvertibleObject(convertibleValue, format, formatProvider, builder);
return true;
}
else
{
if (!string.IsNullOrEmpty(format) && value is IFormattable formattable)
{
builder.Append(formattable.ToString(format, formatProvider));
return true;
}
if (convertToString)
{
SerializeConvertToString(value, formatProvider, builder);
return true;
}
return false;
}
}
private void SerializeConvertibleObject(IConvertible value, string format, IFormatProvider formatProvider, StringBuilder builder)
{
TypeCode convertibleTypeCode = value.GetTypeCode();
if (convertibleTypeCode == TypeCode.String)
{
SerializeStringObject(value.ToString(), format, builder);
return;
}
if (!string.IsNullOrEmpty(format) && value is IFormattable formattable)
{
builder.Append(formattable.ToString(format, formatProvider));
return;
}
switch (convertibleTypeCode)
{
case TypeCode.Boolean:
{
builder.Append(value.ToBoolean(CultureInfo.InvariantCulture) ? "true" : "false");
break;
}
case TypeCode.Char:
{
bool includeQuotes = format != LiteralFormatSymbol;
if (includeQuotes) builder.Append('"');
builder.Append(value.ToChar(CultureInfo.InvariantCulture));
if (includeQuotes) builder.Append('"');
break;
}
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
{
if (value is Enum enumValue)
{
AppendEnumAsString(builder, enumValue);
}
else
{
builder.AppendIntegerAsString(value, convertibleTypeCode);
}
break;
}
case TypeCode.Object: // Guid, TimeSpan, DateTimeOffset
default: // Single, Double, Decimal, etc.
SerializeConvertToString(value, formatProvider, builder);
break;
}
}
private static void SerializeConvertToString(object value, IFormatProvider formatProvider, StringBuilder builder)
{
builder.Append(Convert.ToString(value, formatProvider));
}
private static void SerializeStringObject(string stringValue, string format, StringBuilder builder)
{
bool includeQuotes = format != LiteralFormatSymbol;
if (includeQuotes) builder.Append('"');
builder.Append(stringValue);
if (includeQuotes) builder.Append('"');
}
private void AppendEnumAsString(StringBuilder sb, Enum value)
{
if (!_enumCache.TryGetValue(value, out var textValue))
{
textValue = value.ToString();
_enumCache.TryAddValue(value, textValue);
}
sb.Append(textValue);
}
private bool SerializeWithoutCyclicLoop(IEnumerable collection, string format, IFormatProvider formatProvider, StringBuilder builder,
SingleItemOptimizedHashSet<object> objectsInPath, int depth)
{
if (objectsInPath.Contains(collection))
{
return false; // detected reference loop, skip serialization
}
if (depth > MaxRecursionDepth)
{
return false; // reached maximum recursion level, no further serialization
}
IDictionary dictionary = collection as IDictionary;
if (dictionary != null)
{
using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(dictionary, ref objectsInPath, true, _referenceEqualsComparer))
{
return SerializeDictionaryObject(dictionary, format, formatProvider, builder, objectsInPath, depth);
}
}
using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(collection, ref objectsInPath, true, _referenceEqualsComparer))
{
return SerializeCollectionObject(collection, format, formatProvider, builder, objectsInPath, depth);
}
}
/// <summary>
/// Serialize Dictionary as JSON like structure, without { and }
/// </summary>
/// <example>
/// "FirstOrder"=true, "Previous login"=20-12-2017 14:55:32, "number of tries"=1
/// </example>
/// <param name="dictionary"></param>
/// <param name="format">formatstring of an item</param>
/// <param name="formatProvider"></param>
/// <param name="builder"></param>
/// <param name="objectsInPath"></param>
/// <param name="depth"></param>
/// <returns></returns>
private bool SerializeDictionaryObject(IDictionary dictionary, string format, IFormatProvider formatProvider, StringBuilder builder, SingleItemOptimizedHashSet<object> objectsInPath, int depth)
{
bool separator = false;
foreach (var item in new DictionaryEntryEnumerable(dictionary))
{
if (builder.Length > MaxValueLength)
return false;
if (separator) builder.Append(", ");
SerializeCollectionItem(item.Key, format, formatProvider, builder, ref objectsInPath, depth);
builder.Append("=");
SerializeCollectionItem(item.Value, format, formatProvider, builder, ref objectsInPath, depth);
separator = true;
}
return true;
}
private bool SerializeCollectionObject(IEnumerable collection, string format, IFormatProvider formatProvider, StringBuilder builder, SingleItemOptimizedHashSet<object> objectsInPath, int depth)
{
bool separator = false;
foreach (var item in collection)
{
if (builder.Length > MaxValueLength)
return false;
if (separator) builder.Append(", ");
SerializeCollectionItem(item, format, formatProvider, builder, ref objectsInPath, depth);
separator = true;
}
return true;
}
private void SerializeCollectionItem(object item, string format, IFormatProvider formatProvider, StringBuilder builder, ref SingleItemOptimizedHashSet<object> objectsInPath, int depth)
{
if (item is IConvertible convertible)
SerializeConvertibleObject(convertible, format, formatProvider, builder);
else if (item is IEnumerable enumerable)
SerializeWithoutCyclicLoop(enumerable, format, formatProvider, builder, objectsInPath, depth + 1);
else
SerializeSimpleObject(item, format, formatProvider, builder);
}
/// <summary>
/// Convert a value to a string with format and append to <paramref name="builder"/>.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">Format sting for the value.</param>
/// <param name="formatProvider">Format provider for the value.</param>
/// <param name="builder">Append to this</param>
public static void FormatToString(object value, string format, IFormatProvider formatProvider, StringBuilder builder)
{
var stringValue = value as string;
if (stringValue != null)
{
builder.Append(stringValue);
}
else
{
var formattable = value as IFormattable;
if (formattable != null)
{
builder.Append(formattable.ToString(format, formatProvider));
}
else
{
builder.Append(Convert.ToString(value, formatProvider));
}
}
}
}
}