Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonCropp committed Jun 19, 2024
1 parent e5d4eb0 commit 77134ef
Show file tree
Hide file tree
Showing 9 changed files with 60 additions and 54 deletions.
2 changes: 1 addition & 1 deletion src/Consume/Consume.cs
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ public void CollectionBuilderAttribute()
[CollectionBuilder(typeof(MyCollection), nameof(Create))]
public class MyCollection(ReadOnlySpan<int> initValues)
{
private readonly int[] values = initValues.ToArray();
readonly int[] values = initValues.ToArray();
public IEnumerator<int> GetEnumerator() => ((IEnumerable<int>)values).GetEnumerator();

public static MyCollection Create(ReadOnlySpan<int> values) => new(values);
Expand Down
22 changes: 14 additions & 8 deletions src/Polyfill/Nullability/NullabilityInfoContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,14 @@ sealed class NullabilityInfoContext
[Flags]
enum NotAnnotatedStatus
{
None = 0x0, // no restriction, all members annotated
Private = 0x1, // private members not annotated
Internal = 0x2 // internal members not annotated
// no restriction, all members annotated
None = 0x0,

// private members not annotated
Private = 0x1,

// internal members not annotated
Internal = 0x2
}

NullabilityState? GetNullableContext(MemberInfo? memberInfo)
Expand Down Expand Up @@ -210,7 +215,6 @@ static void CheckNullabilityAttributes(NullabilityInfo nullability, IList<Custom
/// <returns><see cref="NullabilityInfo" /></returns>
public NullabilityInfo Create(PropertyInfo propertyInfo)
{

EnsureIsSupported();

MethodInfo? getter = propertyInfo.GetGetMethod(true);
Expand Down Expand Up @@ -441,10 +445,12 @@ void TryLoadGenericMetaTypeNullability(MemberInfo memberInfo, NullabilityInfo nu
}
}

private static MemberInfo GetMemberMetadataDefinition(MemberInfo member)
static MemberInfo GetMemberMetadataDefinition(MemberInfo member)
{
Type? type = member.DeclaringType;
if ((type != null) && type.IsGenericType && !type.IsGenericTypeDefinition)
if ((type != null) &&
type.IsGenericType &&
!type.IsGenericTypeDefinition)
{
return type.GetGenericTypeDefinition().GetMemberWithSameMetadataDefinitionAs(member);
}
Expand Down Expand Up @@ -639,9 +645,9 @@ static bool IsValueTypeOrValueTypeByRef(Type type) =>

readonly struct NullableAttributeStateParser
{
private static readonly object UnknownByte = (byte)0;
static readonly object UnknownByte = (byte)0;

private readonly object? _nullableAttributeArgument;
readonly object? _nullableAttributeArgument;

public NullableAttributeStateParser(object? nullableAttributeArgument)
{
Expand Down
4 changes: 2 additions & 2 deletions src/Polyfill/Polyfill_Memory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public static Span<char> TrimEnd(this Span<char> target)
/// Delimits all leading occurrences of whitespace charecters from the span.
/// </summary>
/// <param name="span">The source span from which the characters are removed.</param>
private static int ClampStart(ReadOnlySpan<char> target)
static int ClampStart(ReadOnlySpan<char> target)
{
int start = 0;

Expand All @@ -82,7 +82,7 @@ private static int ClampStart(ReadOnlySpan<char> target)
/// </summary>
/// <param name="span">The source span from which the characters are removed.</param>
/// <param name="start">The start index from which to being searching.</param>
private static int ClampEnd(ReadOnlySpan<char> target, int start)
static int ClampEnd(ReadOnlySpan<char> target, int start)
{
int end = target.Length - 1;

Expand Down
2 changes: 1 addition & 1 deletion src/Polyfill/Polyfill_Task.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
static partial class Polyfill
{
// Copied from .NET library const Timer.MaxSupportedTimeout
private const uint MaxSupportedTimeout = 0xfffffffe;
const uint MaxSupportedTimeout = 0xfffffffe;

/// <summary>Gets a <see cref="Task"/> that will complete when this <see cref="Task"/> completes or when the specified <see cref="CancellationToken"/> has cancellation requested.</summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for a cancellation request.</param>
Expand Down
28 changes: 14 additions & 14 deletions src/Polyfill/Regex/RegexCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,28 +29,28 @@ internal sealed class RegexCache
// about such costs, it should either increase Regex.CacheSize or do its own Regex instance caching.

/// <summary>The default maximum number of items to store in the cache.</summary>
private const int DefaultMaxCacheSize = 15;
const int DefaultMaxCacheSize = 15;
/// <summary>The maximum number of cached items to examine when we need to replace an existing one in the cache with a new one.</summary>
/// <remarks>This is a somewhat arbitrary value, chosen to be small but at least as large as DefaultMaxCacheSize.</remarks>
private const int MaxExamineOnDrop = 30;
const int MaxExamineOnDrop = 30;

/// <summary>A read-through cache of one element, representing the most recently used regular expression.</summary>
private static volatile Node? s_lastAccessed;
static volatile Node? s_lastAccessed;
/// <summary>The thread-safe dictionary storing all the items in the cache.</summary>
/// <remarks>
/// The concurrency level is initialized to 1 as we're using our own global lock for all mutations, so we don't need ConcurrentDictionary's
/// striped locking. Capacity is initialized to 31, which is the same as (the private) ConcurrentDictionary.DefaultCapacity.
/// </remarks>
private static readonly ConcurrentDictionary<Key, Node> s_cacheDictionary = new ConcurrentDictionary<Key, Node>(concurrencyLevel: 1, capacity: 31);
static readonly ConcurrentDictionary<Key, Node> s_cacheDictionary = new ConcurrentDictionary<Key, Node>(concurrencyLevel: 1, capacity: 31);
/// <summary>A list of all the items in the cache. Protected by <see cref="SyncObj"/>.</summary>
private static readonly List<Node> s_cacheList = new List<Node>(DefaultMaxCacheSize);
static readonly List<Node> s_cacheList = new List<Node>(DefaultMaxCacheSize);
/// <summary>Random number generator used to examine a subset of items when we need to drop one from a large list. Protected by <see cref="SyncObj"/>.</summary>
private static readonly Random s_random = new Random();
static readonly Random s_random = new Random();
/// <summary>The current maximum number of items allowed in the cache. This rarely changes. Mostly protected by <see cref="SyncObj"/>.</summary>
private static int s_maxCacheSize = DefaultMaxCacheSize;
static int s_maxCacheSize = DefaultMaxCacheSize;

/// <summary>Lock used to protect shared state on mutations.</summary>
private static object SyncObj => s_cacheDictionary;
static object SyncObj => s_cacheDictionary;

/// <summary>Gets or sets the maximum size of the cache.</summary>
public static int MaxCacheSize
Expand Down Expand Up @@ -131,7 +131,7 @@ public static Regex GetOrAdd(string pattern, RegexOptions options, TimeSpan matc
return regex;
}

private static Regex? Get(Key key)
static Regex? Get(Key key)
{
long lastAccessedStamp = 0;

Expand Down Expand Up @@ -175,7 +175,7 @@ public static Regex GetOrAdd(string pattern, RegexOptions options, TimeSpan matc
return null;
}

private static void Add(Key key, Regex regex)
static void Add(Key key, Regex regex)
{
lock (SyncObj)
{
Expand Down Expand Up @@ -250,9 +250,9 @@ private static void Add(Key key, Regex regex)
/// <summary>Used as a key for <see cref="Node"/>.</summary>
internal readonly struct Key : IEquatable<Key>
{
private readonly string _pattern;
private readonly RegexOptions _options;
private readonly TimeSpan _matchTimeout;
readonly string _pattern;
readonly RegexOptions _options;
readonly TimeSpan _matchTimeout;

public Key(string pattern, RegexOptions options, TimeSpan matchTimeout)
{
Expand All @@ -278,7 +278,7 @@ public override int GetHashCode() =>
}

/// <summary>Node for a cached Regex instance.</summary>
private sealed class Node(Key key, Regex regex)
sealed class Node(Key key, Regex regex)
{
/// <summary>The key associated with this cached instance.</summary>
public readonly Key Key = key;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ struct AppendInterpolatedStringHandler
// in a variety of places, e.g. allowing a null input when one isn't expected to produce a NullReferenceException rather
// than an ArgumentNullException.

private const int StackallocCharBufferSizeLimit = 256;
const int StackallocCharBufferSizeLimit = 256;

/// <summary>The associated StringBuilder to which to append.</summary>
private readonly StringBuilder _stringBuilder;
readonly StringBuilder _stringBuilder;

/// <summary>Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls.</summary>
private readonly IFormatProvider? _provider;
readonly IFormatProvider? _provider;

/// <summary>Whether <see cref="_provider"/> provides an ICustomFormatter.</summary>
/// <remarks>
Expand All @@ -43,7 +43,7 @@ struct AppendInterpolatedStringHandler
/// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a
/// formatter, we pay for the extra interface call on each AppendFormatted that needs it.
/// </remarks>
private readonly bool _hasCustomFormatter;
readonly bool _hasCustomFormatter;

/// <summary>Creates a handler used to append an interpolated string into a <see cref="StringBuilder"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
Expand Down Expand Up @@ -204,7 +204,7 @@ public void AppendFormatted<T>(T value, int alignment, string? format)
}

/// <summary>Formats into temporary space and then appends the result into the StringBuilder.</summary>
private void AppendFormattedWithTempSpace<T>(T value, int alignment, string? format)
void AppendFormattedWithTempSpace<T>(T value, int alignment, string? format)
{
// It's expected that either there's not enough space in the current chunk to store this formatted value,
// or we have a non-0 alignment that could require padding inserted. So format into temporary space and
Expand Down Expand Up @@ -322,7 +322,7 @@ public void AppendFormatted(object? value, int alignment = 0, string? format = n
/// <param name="format">The format string.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
[MethodImpl(MethodImplOptions.NoInlining)]
private void AppendCustomFormatter<T>(T value, string? format)
void AppendCustomFormatter<T>(T value, string? format)
{
// This case is very rare, but we need to handle it prior to the other checks in case
// a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value.
Expand All @@ -340,7 +340,7 @@ private void AppendCustomFormatter<T>(T value, string? format)
}
}

private static bool HasTryFormatExtension(Type type) =>
static bool HasTryFormatExtension(Type type) =>
type == typeof(int) || type == typeof(bool) || type == typeof(byte) || type == typeof(float) ||
type == typeof(double) || type == typeof(DateTime) || type == typeof(DateTimeOffset) ||
type == typeof(decimal) || type == typeof(long) || type == typeof(short) || type == typeof(ushort) ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,23 +38,23 @@ ref struct DefaultInterpolatedStringHandler
/// numbers of items, we bump the 8 up to 11 to account for the three extra characters in "{d}",
/// since the compiler-provided base length won't include the equivalent character count.
/// </remarks>
private const int GuessedLengthPerHole = 11;
const int GuessedLengthPerHole = 11;
/// <summary>Minimum size array to rent from the pool.</summary>
/// <remarks>Same as stack-allocation size used today by string.Format.</remarks>
private const int MinimumArrayPoolLength = 256;
const int MinimumArrayPoolLength = 256;

/// <summary>Maximum length allowed for a string.</summary>
/// <remarks>Keep in sync with AllocateString in gchelpers.cpp.</remarks>
private const int StringMaxLength = 0x3FFFFFDF;
const int StringMaxLength = 0x3FFFFFDF;

/// <summary>Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls.</summary>
private readonly IFormatProvider? _provider;
readonly IFormatProvider? _provider;
/// <summary>Array rented from the array pool and used to back <see cref="_chars"/>.</summary>
private char[]? _arrayToReturnToPool;
char[]? _arrayToReturnToPool;
/// <summary>The span to write into.</summary>
private Span<char> _chars;
Span<char> _chars;
/// <summary>Position at which to write the next character.</summary>
private int _pos;
int _pos;
/// <summary>Whether <see cref="_provider"/> provides an ICustomFormatter.</summary>
/// <remarks>
/// Custom formatters are very rare. We want to support them, but it's ok if we make them more expensive
Expand All @@ -63,7 +63,7 @@ ref struct DefaultInterpolatedStringHandler
/// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a
/// formatter, we pay for the extra interface call on each AppendFormatted that needs it.
/// </remarks>
private readonly bool _hasCustomFormatter;
readonly bool _hasCustomFormatter;

/// <summary>Creates a handler used to translate an interpolated string into a <see cref="string"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
Expand Down Expand Up @@ -474,7 +474,7 @@ value is not null &&
/// or a string that doesn't fit in the current buffer.
/// </remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
private void AppendFormattedSlow(string? value)
void AppendFormattedSlow(string? value)
{
if (_hasCustomFormatter)
{
Expand Down Expand Up @@ -537,7 +537,7 @@ internal static bool HasCustomFormatter(IFormatProvider provider)
/// <param name="format">The format string.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
[MethodImpl(MethodImplOptions.NoInlining)]
private void AppendCustomFormatter<T>(T value, string? format)
void AppendCustomFormatter<T>(T value, string? format)
{
// This case is very rare, but we need to handle it prior to the other checks in case
// a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value.
Expand All @@ -563,7 +563,7 @@ private void AppendCustomFormatter<T>(T value, string? format)
/// Non-zero minimum number of characters that should be written for this value. If the value is negative, it
/// indicates left-aligned and the required minimum is the absolute value.
/// </param>
private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)
void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)
{
Debug.Assert(startingPos >= 0 && startingPos <= _pos);
Debug.Assert(alignment != 0);
Expand Down Expand Up @@ -600,7 +600,7 @@ private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)
/// Ensures <see cref="_chars"/> has the capacity to store <paramref name="additionalChars"/> beyond <see cref="_pos"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacityForAdditionalChars(int additionalChars)
void EnsureCapacityForAdditionalChars(int additionalChars)
{
if (_chars.Length - _pos < additionalChars)
{
Expand All @@ -613,7 +613,7 @@ private void EnsureCapacityForAdditionalChars(int additionalChars)
/// </summary>
/// <param name="value">The string to write.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void GrowThenCopyString(string value)
void GrowThenCopyString(string value)
{
Grow(value.Length);
value.CopyTo(_chars.Slice(_pos));
Expand All @@ -625,7 +625,7 @@ private void GrowThenCopyString(string value)
/// </summary>
/// <param name="value">The span to write.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void GrowThenCopySpan(scoped ReadOnlySpan<char> value)
void GrowThenCopySpan(scoped ReadOnlySpan<char> value)
{
Grow(value.Length);
value.CopyTo(_chars.Slice(_pos));
Expand All @@ -637,7 +637,7 @@ private void GrowThenCopySpan(scoped ReadOnlySpan<char> value)
/// beyond <see cref="_pos"/>.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible
private void Grow(int additionalChars)
void Grow(int additionalChars)
{
// This method is called when the remaining space (_chars.Length - _pos) is
// insufficient to store a specific number of additional characters. Thus, we
Expand All @@ -649,7 +649,7 @@ private void Grow(int additionalChars)

/// <summary>Grows the size of <see cref="_chars"/>.</summary>
[MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible
private void Grow() =>
void Grow() =>
// This method is called when the remaining space in _chars isn't sufficient to continue
// the operation. Thus, we need at least one character beyond _chars.Length. GrowCore
// will handle growing by more than that if possible.
Expand All @@ -659,7 +659,7 @@ private void Grow() =>
/// Grow the size of <see cref="_chars"/> to at least the specified <paramref name="requiredMinCapacity"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // but reuse this grow logic directly in both of the above grow routines
private void GrowCore(uint requiredMinCapacity)
void GrowCore(uint requiredMinCapacity)
{
// We want the max of how much space we actually required and doubling our capacity (without going beyond
// the max allowed length). We also want to avoid asking for small arrays, to reduce the number of times we
Expand All @@ -682,7 +682,7 @@ private void GrowCore(uint requiredMinCapacity)
}
}

private bool TryFormatWithExtensions<T>(T value, ReadOnlySpan<char> format)
bool TryFormatWithExtensions<T>(T value, ReadOnlySpan<char> format)
{
int charsWritten;
switch (value)
Expand Down Expand Up @@ -804,7 +804,7 @@ public static uint Clamp(uint value, uint min, uint max)
}

[DoesNotReturn]
private static void ThrowMinMaxException<T>(T min, T max) =>
static void ThrowMinMaxException<T>(T min, T max) =>
throw new ArgumentException(string.Format(SR.Argument_MinMaxValue, min, max));
}

Expand Down
2 changes: 1 addition & 1 deletion src/Tests/CollectionBuilderAttributeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public void CollectionBuilderAttributeTests_Compatibility_with_all_TargetFramewo
[CollectionBuilder(typeof(MyCollection), nameof(Create))]
public class MyCollection(ReadOnlySpan<int> initValues)
{
private readonly int[] values = initValues.ToArray();
readonly int[] values = initValues.ToArray();
public IEnumerator<int> GetEnumerator() => ((IEnumerable<int>)values).GetEnumerator();

public static MyCollection Create(ReadOnlySpan<int> values) => new(values);
Expand Down
2 changes: 1 addition & 1 deletion src/Tests/PolyfillTests_CancellationTokenSource.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
partial class PolyfillTests
{
private static bool IsCompletedSuccessfully(Task task)
static bool IsCompletedSuccessfully(Task task)
{
#if NETFRAMEWORK || NETSTANDARD
return task.Status == TaskStatus.RanToCompletion;
Expand Down

0 comments on commit 77134ef

Please sign in to comment.