Skip to content

Commit 429d87a

Browse files
committed
chore: Add common shims for new language features
Handful of commonly used shim types to unlock new(-ish) language features in older TFMs. Limited to features that are only gated by symbol existence checks, but covers some fairly common features. Signed-off-by: Austin Drenski <[email protected]>
1 parent 1a14f6c commit 429d87a

9 files changed

+603
-2
lines changed

.github/workflows/dotnet-format.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,4 @@ jobs:
2727
run: dotnet tool install -g dotnet-format
2828

2929
- name: dotnet format
30-
run: dotnet-format --folder --check
30+
run: dotnet-format --folder --check --exclude src/Shared/

build/Common.prod.props

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,8 @@
4040
<PropertyGroup Condition="'$(Deterministic)'=='true'">
4141
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
4242
</PropertyGroup>
43+
44+
<ItemGroup>
45+
<Compile Include="$(MSBuildThisFileDirectory)../src/Shared/**" LinkBase="Shared" />
46+
</ItemGroup>
4347
</Project>

build/Common.props

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<Project>
22
<PropertyGroup>
3-
<LangVersion>7.3</LangVersion>
3+
<LangVersion>latest</LangVersion>
44
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
55
<EnableNETAnalyzers>true</EnableNETAnalyzers>
66
</PropertyGroup>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#nullable enable
2+
// @formatter:off
3+
// ReSharper disable All
4+
#if NETCOREAPP3_0_OR_GREATER
5+
// https://github.com/dotnet/runtime/issues/96197
6+
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.CallerArgumentExpressionAttribute))]
7+
#else
8+
#pragma warning disable
9+
// Licensed to the .NET Foundation under one or more agreements.
10+
// The .NET Foundation licenses this file to you under the MIT license.
11+
12+
namespace System.Runtime.CompilerServices
13+
{
14+
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
15+
internal sealed class CallerArgumentExpressionAttribute : Attribute
16+
{
17+
public CallerArgumentExpressionAttribute(string parameterName)
18+
{
19+
ParameterName = parameterName;
20+
}
21+
22+
public string ParameterName { get; }
23+
}
24+
}
25+
#endif

src/Shared/Check.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#nullable enable
2+
using System;
3+
using System.Diagnostics;
4+
using System.Runtime.CompilerServices;
5+
6+
namespace OpenFeature;
7+
8+
[DebuggerStepThrough]
9+
static class Check
10+
{
11+
public static T NotNull<T>(T? value, [CallerArgumentExpression("value")] string name = null!)
12+
{
13+
#if NET8_0_OR_GREATER
14+
ArgumentNullException.ThrowIfNull(value, name);
15+
#else
16+
if (value is null)
17+
throw new ArgumentNullException(name);
18+
#endif
19+
20+
return value;
21+
}
22+
}

src/Shared/Index.cs

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
#nullable enable
2+
// @formatter:off
3+
// ReSharper disable All
4+
#if NET5_0_OR_GREATER
5+
// https://github.com/dotnet/runtime/issues/96197
6+
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Index))]
7+
#else
8+
#pragma warning disable
9+
// Licensed to the .NET Foundation under one or more agreements.
10+
// The .NET Foundation licenses this file to you under the MIT license.
11+
12+
using System.Diagnostics;
13+
using System.Diagnostics.CodeAnalysis;
14+
using System.Runtime.CompilerServices;
15+
16+
namespace System
17+
{
18+
/// <summary>Represent a type can be used to index a collection either from the start or the end.</summary>
19+
/// <remarks>
20+
/// Index is used by the C# compiler to support the new index syntax
21+
/// <code>
22+
/// int[] someArray = new int[5] { 1, 2, 3, 4, 5 } ;
23+
/// int lastElement = someArray[^1]; // lastElement = 5
24+
/// </code>
25+
/// </remarks>
26+
readonly struct Index : IEquatable<Index>
27+
{
28+
private readonly int _value;
29+
30+
/// <summary>Construct an Index using a value and indicating if the index is from the start or from the end.</summary>
31+
/// <param name="value">The index value. it has to be zero or positive number.</param>
32+
/// <param name="fromEnd">Indicating if the index is from the start or from the end.</param>
33+
/// <remarks>
34+
/// If the Index constructed from the end, index value 1 means pointing at the last element and index value 0 means pointing at beyond last element.
35+
/// </remarks>
36+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
37+
public Index(int value, bool fromEnd = false)
38+
{
39+
if (value < 0)
40+
{
41+
// ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException();
42+
throw new ArgumentOutOfRangeException(nameof(value));
43+
}
44+
45+
if (fromEnd)
46+
_value = ~value;
47+
else
48+
_value = value;
49+
}
50+
51+
// The following private constructors mainly created for perf reason to avoid the checks
52+
private Index(int value)
53+
{
54+
_value = value;
55+
}
56+
57+
/// <summary>Create an Index pointing at first element.</summary>
58+
public static Index Start => new Index(0);
59+
60+
/// <summary>Create an Index pointing at beyond last element.</summary>
61+
public static Index End => new Index(~0);
62+
63+
/// <summary>Create an Index from the start at the position indicated by the value.</summary>
64+
/// <param name="value">The index value from the start.</param>
65+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
66+
public static Index FromStart(int value)
67+
{
68+
if (value < 0)
69+
{
70+
// ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException();
71+
throw new ArgumentOutOfRangeException(nameof(value));
72+
}
73+
74+
return new Index(value);
75+
}
76+
77+
/// <summary>Create an Index from the end at the position indicated by the value.</summary>
78+
/// <param name="value">The index value from the end.</param>
79+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
80+
public static Index FromEnd(int value)
81+
{
82+
if (value < 0)
83+
{
84+
// ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException();
85+
throw new ArgumentOutOfRangeException(nameof(value));
86+
}
87+
88+
return new Index(~value);
89+
}
90+
91+
/// <summary>Returns the index value.</summary>
92+
public int Value
93+
{
94+
get
95+
{
96+
if (_value < 0)
97+
return ~_value;
98+
else
99+
return _value;
100+
}
101+
}
102+
103+
/// <summary>Indicates whether the index is from the start or the end.</summary>
104+
public bool IsFromEnd => _value < 0;
105+
106+
/// <summary>Calculate the offset from the start using the giving collection length.</summary>
107+
/// <param name="length">The length of the collection that the Index will be used with. length has to be a positive value</param>
108+
/// <remarks>
109+
/// For performance reason, we don't validate the input length parameter and the returned offset value against negative values.
110+
/// we don't validate either the returned offset is greater than the input length.
111+
/// It is expected Index will be used with collections which always have non negative length/count. If the returned offset is negative and
112+
/// then used to index a collection will get out of range exception which will be same affect as the validation.
113+
/// </remarks>
114+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
115+
public int GetOffset(int length)
116+
{
117+
int offset = _value;
118+
if (IsFromEnd)
119+
{
120+
// offset = length - (~value)
121+
// offset = length + (~(~value) + 1)
122+
// offset = length + value + 1
123+
124+
offset += length + 1;
125+
}
126+
return offset;
127+
}
128+
129+
/// <summary>Indicates whether the current Index object is equal to another object of the same type.</summary>
130+
/// <param name="value">An object to compare with this object</param>
131+
public override bool Equals([NotNullWhen(true)] object? value) => value is Index && _value == ((Index)value)._value;
132+
133+
/// <summary>Indicates whether the current Index object is equal to another Index object.</summary>
134+
/// <param name="other">An object to compare with this object</param>
135+
public bool Equals(Index other) => _value == other._value;
136+
137+
/// <summary>Returns the hash code for this instance.</summary>
138+
public override int GetHashCode() => _value;
139+
140+
/// <summary>Converts integer number to an Index.</summary>
141+
public static implicit operator Index(int value) => FromStart(value);
142+
143+
/// <summary>Converts the value of the current Index object to its equivalent string representation.</summary>
144+
public override string ToString()
145+
{
146+
if (IsFromEnd)
147+
return ToStringFromEnd();
148+
149+
return ((uint)Value).ToString();
150+
}
151+
152+
private string ToStringFromEnd()
153+
{
154+
#if (!NETSTANDARD2_0 && !NETFRAMEWORK)
155+
Span<char> span = stackalloc char[11]; // 1 for ^ and 10 for longest possible uint value
156+
bool formatted = ((uint)Value).TryFormat(span.Slice(1), out int charsWritten);
157+
Debug.Assert(formatted);
158+
span[0] = '^';
159+
return new string(span.Slice(0, charsWritten + 1));
160+
#else
161+
return '^' + Value.ToString();
162+
#endif
163+
}
164+
}
165+
}
166+
#endif

src/Shared/IsExternalInit.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#nullable enable
2+
// @formatter:off
3+
// ReSharper disable All
4+
#if NET5_0_OR_GREATER
5+
// https://github.com/dotnet/runtime/issues/96197
6+
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsExternalInit))]
7+
#else
8+
#pragma warning disable
9+
// Licensed to the .NET Foundation under one or more agreements.
10+
// The .NET Foundation licenses this file to you under the MIT license.
11+
12+
using System.ComponentModel;
13+
14+
namespace System.Runtime.CompilerServices
15+
{
16+
/// <summary>
17+
/// Reserved to be used by the compiler for tracking metadata.
18+
/// This class should not be used by developers in source code.
19+
/// </summary>
20+
[EditorBrowsable(EditorBrowsableState.Never)]
21+
static class IsExternalInit
22+
{
23+
}
24+
}
25+
#endif

0 commit comments

Comments
 (0)