-
Notifications
You must be signed in to change notification settings - Fork 368
/
Formatter{T}.cs
93 lines (79 loc) · 2.72 KB
/
Formatter{T}.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
namespace Microsoft.DotNet.Interactive.Formatting;
/// <summary>
/// Provides formatting functionality for a specific type.
/// </summary>
/// <typeparam name="T">The type for which formatting is provided.</typeparam>
public static class Formatter<T>
{
internal static readonly bool TypeIsAnonymous;
internal static readonly bool TypeIsTuple;
internal static readonly bool TypeIsValueTuple;
internal static readonly bool TypeIsTupleOfScalars;
internal static readonly bool TypeIsScalar;
private static int? _listExpansionLimit;
/// <summary>
/// Initializes the <see cref="Formatter<T>"/> class.
/// </summary>
static Formatter()
{
if (TypeIsScalar = typeof(T).IsScalar())
{
}
else if (TypeIsTuple = typeof(T).IsTuple())
{
var fieldTypes = typeof(T).GetProperties().Select(p => p.PropertyType);
TypeIsTupleOfScalars = fieldTypes.All(t => t.IsScalar());
}
else if (TypeIsValueTuple = typeof(T).IsValueTuple())
{
var fieldTypes = typeof(T).GetFields().Select(f => f.FieldType);
TypeIsTupleOfScalars = fieldTypes.All(t => t.IsScalar());
}
else
{
TypeIsAnonymous = typeof(T).IsAnonymous();
}
void Initialize()
{
_listExpansionLimit = null;
}
Initialize();
Formatter.Clearing += Initialize;
}
/// <summary>
/// Formats an object and writes it to the specified writer.
/// </summary>
/// <param name="obj">The object to be formatted.</param>
/// <param name="context">The context for the current format operation.</param>
/// <param name="mimeType">The mime type to format to.</param>
public static void FormatTo(
T obj,
FormatContext context,
string mimeType = PlainTextFormatter.MimeType)
{
if (obj is null)
{
var formatter = Formatter.GetPreferredFormatterFor(typeof(T), mimeType);
formatter.Format(null, context);
return;
}
using var _ = context.IncrementDepth();
if (context.AllowRecursion)
{
var formatter = Formatter.GetPreferredFormatterFor(typeof(T), mimeType);
formatter.Format(obj, context);
}
else
{
PlainTextFormatter<T>.Default.Format(obj, context);
}
}
public static int ListExpansionLimit
{
get => _listExpansionLimit ?? Formatter.ListExpansionLimit;
set => _listExpansionLimit = value;
}
}