Skip to content

Commit

Permalink
v13.0.0 - Bring more bits from client projects
Browse files Browse the repository at this point in the history
  • Loading branch information
monoman committed Nov 8, 2023
1 parent 98a9f78 commit ba414e4
Show file tree
Hide file tree
Showing 10 changed files with 84 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ private static void TestSkippingOn(Stream baseStream) {
_ = baseStream.Seek(10, SeekOrigin.Begin);
Assert.AreEqual(10L, baseStream.Position);
using (var sp = new StreamSpan(baseStream, (ulong)baseStream.ReadByte())) {
if (sp.CanSeek)
if (sp.CanSeek)
Assert.AreEqual("[30] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ", sp.DEBUG_SomeBytes);
else
Assert.AreEqual(StreamSpan.NonSeekable, sp.DEBUG_SomeBytes);
Expand Down Expand Up @@ -121,11 +121,8 @@ private static void TestSkippingOn(Stream baseStream) {
Assert.AreEqual(baseStream.Length, baseStream.Position);
}

private class NonSeekMemoryStream : MemoryStream
private class NonSeekMemoryStream(byte[] buffer) : MemoryStream(buffer, writable: true)
{
public NonSeekMemoryStream(byte[] buffer) : base(buffer, writable: true) {
}

public override bool CanSeek => false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public static class IEnumerableOfClassExtensions
public static IEnumerable<T> NonNulls<T>(this IEnumerable<T?>? values) where T : class
=> values.Safe().Skip(item => item is null)!;

public static T[] NonEmpty<T>([NotNull] this T[] items, [CallerArgumentExpression("items")] string? parameterName = null) =>
public static T[] NonEmpty<T>([NotNull] this T[] items, [CallerArgumentExpression(nameof(items))] string? parameterName = null) =>
items is null || items.Length == 0 ? throw new ArgumentException("Should not be empty", parameterName) : items;

}
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,8 @@ private static T ReadNumber<T>(TextReader reader, ulong maxValue, Func<ulong, T>
if (value > maxValue)
throw new InvalidOperationException("Number is too big");
else {
T castValue = cast(value);
var castValue = cast(value);
return isNegative ? -castValue : castValue;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ public static IEnumerable<T> _<T>(this T item, T secondItem) =>

public static bool AnyWithNoNulls<T>([NotNullWhen(true)] this IEnumerable<T> items) => items.SafeAny() && items.NoNulls();

public static IEnumerable<T> Append<T>(this IEnumerable<T>? first, params T[] extras) =>
first.Safe().Concat(extras);
public static IEnumerable<T> Append<T>(this IEnumerable<T>? list, params T[] extras) =>
list.Safe().Concat(extras);

public static IEnumerable<T> Append<T>(this IEnumerable<T>? first, IEnumerable<T> second) =>
first.Safe().Concat(second);
public static IEnumerable<T> Append<T>(this IEnumerable<T>? list, IEnumerable<T> extras) =>
list.Safe().Concat(extras);

public static IEnumerable<T> AppendedOf<T>(this T item, IEnumerable<T> remainingItems) =>
InnerAppend(item, remainingItems);
Expand All @@ -63,8 +63,8 @@ public static bool EqualTo<T>(this IEnumerable<T>? first, IEnumerable<T>? second
public static bool EquivalentTo<T>(this IEnumerable<T>? first, IEnumerable<T> second) =>
first.Safe().SequenceEqual(second.Safe());

public static IEnumerable<T> ExceptFor<T>(this IEnumerable<T>? first, params T[] exceptions) =>
first.Safe().Except(exceptions);
public static IEnumerable<T> ExceptFor<T>(this IEnumerable<T>? list, params T[] exceptions) =>
list.Safe().Except(exceptions);

public static IEnumerable<T> FilledTo<T>(this IEnumerable<T>? list, int length, T filler) {
if (list.SafeAny())
Expand Down Expand Up @@ -97,7 +97,7 @@ public static string JoinedBy<T>(this IEnumerable<T>? list, string joiner, Func<

public static bool None<T>([NotNullWhen(false)] this IEnumerable<T>? items, Func<T, bool> predicate) => !items.SafeAny(predicate);

public static IEnumerable<T> NonEmpty<T>([NotNull] this IEnumerable<T> items, [CallerArgumentExpression("items")] string? parameterName = null) =>
public static IEnumerable<T> NonEmpty<T>([NotNull] this IEnumerable<T> items, [CallerArgumentExpression(nameof(items))] string? parameterName = null) =>
items.SafeAny() ? items : throw new ArgumentException("Should not be empty", parameterName);

public static bool NoNulls<T>(this IEnumerable<T>? items) => items.None(item => item is null);
Expand Down Expand Up @@ -141,8 +141,10 @@ public static IEnumerable<T> SafeConcat<T>(this IEnumerable<T>? items, IEnumerab

public static int SafeCount<T>(this IEnumerable<T>? values) => values?.Count() ?? -1;

public static IEnumerable<TResult> SelectSkippingNulls<TSource, TResult>(this IEnumerable<TSource>? values, Func<TSource, TResult> selector) where TResult : class =>
Safe(values?.Select(selector).SkipNulls());
public static IEnumerable<TResult> SelectSkippingNulls<TSource, TResult>(this IEnumerable<TSource?>? values, Func<TSource, TResult?> selector)
where TSource : class
where TResult : class =>
values.SkipNulls().Select(selector).SkipNulls()!;

public static IEnumerable<T> Skip<T>(this IEnumerable<T>? values, Func<T, bool> predicate) =>
values.Safe().Where(item => !predicate(item));
Expand All @@ -154,8 +156,8 @@ public static IEnumerable<T> Skip<T>(this IEnumerable<T>? values, Func<T, bool>
public static IEnumerable<T> SkipNonNulls<T>(this IEnumerable<T>? values) where T : class =>
values.Skip(item => item is not null);

public static IEnumerable<T> SkipNulls<T>(this IEnumerable<T>? values) where T : class =>
values.Skip(item => item is null);
public static IEnumerable<T> SkipNulls<T>(this IEnumerable<T?>? values) where T : class =>
values.Skip(item => item is null)!;

public static IEnumerable<T> TakeULong<T>(this IEnumerable<T>? items, ulong howMany) =>
(howMany <= int.MaxValue) ? items.Safe().Take((int)howMany) : items.Safe();
Expand Down
22 changes: 22 additions & 0 deletions InterlockLedger.Commons/Extensions/System/ArrayOfTExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,26 @@ public static class ArrayOfTExtensions
{
public static string JoinedBy<T>(this T[]? values, string joiner) =>
string.Join(joiner, values.Safe().ToStrings());

[return: NotNull]
public static T[] OrEmpty<T>(this T[]? values) =>
values ?? Array.Empty<T>();

[return: NotNull]
public static T[] MinLength<T>([NotNull] this T[] array, int length, [CallerArgumentExpression(nameof(array))] string? parameterName = null) =>
array is not null && array.Length >= length
? array
: throw new ArgumentException($"Array parameter {parameterName} must have length >= {length}");

[return: NotNull]
public static T[] MaxLength<T>([NotNull] this T[] array, int length, [CallerArgumentExpression(nameof(array))] string? parameterName = null) =>
array is not null && array.Length <= length
? array
: throw new ArgumentException($"Array parameter {parameterName} must have length <= {length}");

[return: NotNull]
public static T[] ExactLength<T>([NotNull] this T[] array, int length, [CallerArgumentExpression(nameof(array))] string? parameterName = null) =>
array is not null && array.Length == length
? array
: throw new ArgumentException($"Array parameter {parameterName} must have length == {length}");
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ namespace System;

public static class NullableOfStructExtensions
{
public static T Required<T>(this T? value, [CallerArgumentExpression("value")] string? name = null) where T : struct
public static T Required<T>(this T? value, [CallerArgumentExpression(nameof(value))] string? name = null) where T : struct
=> value ?? throw new ArgumentException("Required", name);
}
8 changes: 6 additions & 2 deletions InterlockLedger.Commons/Extensions/System/ObjectExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,16 @@
//
// ******************************************************************************************************************************

using System.Text.Json;

namespace System;



public static class ObjectExtensions
{
public static string AsJson<T>(this T json) => JsonSerializer.Serialize<T>(json, StringExtensions.DefaultJsonOptions);

public static IEnumerable<T> AsSingle<T>(this T s) =>
new SingleEnumerable<T>(s);

Expand All @@ -60,11 +64,11 @@ public static bool IsDefault<T>(this T value) =>
public static string? PadRight(this object? value, int totalWidth) =>
value?.ToString()?.PadRight(totalWidth);

public static T Required<T>([NotNull] this T? value, [CallerArgumentExpression("value")] string? name = null)
public static T Required<T>([NotNull] this T? value, [CallerArgumentExpression(nameof(value))] string? name = null)
where T : class =>
value ?? throw ArgRequired(name);

public static T RequiredUsing<T>([NotNull] this T? value, Func<string?, Exception> exceptor, [CallerArgumentExpression("value")] string? name = null)
public static T RequiredUsing<T>([NotNull] this T? value, Func<string?, Exception> exceptor, [CallerArgumentExpression(nameof(value))] string? name = null)
where T : class =>
value ?? throw exceptor.Required()(name);

Expand Down
22 changes: 20 additions & 2 deletions InterlockLedger.Commons/Extensions/System/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,25 @@
//
// ******************************************************************************************************************************

using System.Text.Json;

using static System.ObjectExtensions;

namespace System;

public static partial class StringExtensions
{
public static JsonSerializerOptions DefaultJsonOptions { get; } = new JsonSerializerOptions {
AllowTrailingCommas = true,
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
IgnoreReadOnlyProperties = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
};

public static string Safe(this string? value) =>
string.IsNullOrWhiteSpace(value)
? string.Empty
Expand Down Expand Up @@ -107,10 +120,10 @@ public static string ParenthesizeIf(this string s, bool condition = false) =>
public static string? RegexReplace(this string? value, string pattern, MatchEvaluator me) =>
value.SafeTransform(s => Regex.Replace(s, pattern, me));

public static string Required([NotNull] this string? value, [CallerArgumentExpression("value")] string? name = null) =>
public static string Required([NotNull] this string? value, [CallerArgumentExpression(nameof(value))] string? name = null) =>
value.IsBlank() ? throw ArgRequired(name) : value;

public static string RequiredUsing([NotNull] this string? value, Func<string?, Exception> exceptor, [CallerArgumentExpression("value")] string? name = null) =>
public static string RequiredUsing([NotNull] this string? value, Func<string?, Exception> exceptor, [CallerArgumentExpression(nameof(value))] string? name = null) =>
value.IsBlank() ? throw exceptor.Required()(name) : value;

public static string Reversed(this string s) =>
Expand Down Expand Up @@ -216,4 +229,9 @@ private static string ToUpperInvariant(Match match) =>

[GeneratedRegex("""[\r\n\s]+""")]
private static partial Regex WhiteSpaceRegex();

public static T? FromJson<T>(this string json) =>
string.IsNullOrWhiteSpace(json) ? default : JsonSerializer.Deserialize<T>(json, DefaultJsonOptions);


}
4 changes: 2 additions & 2 deletions InterlockLedger.Commons/InterlockLedger.Commons.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
<Product>InterlockLedger</Product>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/interlockledger/interlockledger-commons.git</RepositoryUrl>
<Version>12.4.0</Version>
<Version>13.0.0</Version>
<PackageId>InterlockLedger.Commons</PackageId>
<PackageReleaseNotes>Fix for debugging helper on StreamSpan for bigger streams</PackageReleaseNotes>
<PackageReleaseNotes>Bring more bits from client projects</PackageReleaseNotes>
<PackageIcon>il2.png</PackageIcon>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
Expand Down
26 changes: 15 additions & 11 deletions InterlockLedger.Commons/Types/System/AbstractDisposable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ namespace System;

public abstract class AbstractDisposable : IDisposable
{
public const string DisposedJustification = "Disposed by overriding AbstractDisposable.DisposeManagedResources";

[JsonIgnore]
public bool Disposed => _disposed != 0;

public void Dispose() {
Expand All @@ -47,25 +46,30 @@ public void Dispose() {

protected virtual void DisposeUnmanagedResources() { }

protected T Do<T>(Func<T> function, T @default = default) where T : struct =>
!Disposed ? function.Required()() : @default;
protected T? UnsafeDo<T>(Func<T?> function, T? @default = default) where T : class =>
!Disposed ? function.Required()() : @default;

protected void Do(Action action) {
if (!Disposed) action.Required()();
}
protected T Do<T>(Func<T> function, T @default = default) where T : struct =>
Disposed ? @default : function.Required()();
protected T? UnsafeDo<T>(Func<T?> function, T? @default = default) where T : class =>
Disposed ? @default : function.Required()();
protected T? UnsafeDo<T>(Func<T?> function) =>
Disposed ? default : function.Required()();

protected async Task<T> DoAsync<T>(Func<Task<T>> function, T @default = default) where T : struct =>
!Disposed ? await function.Required()().ConfigureAwait(false) : @default;
protected async Task<T?> UnsafeDoAsync<T>(Func<Task<T?>> function, T? @default = default) where T : class =>
!Disposed ? await function.Required()().ConfigureAwait(false) : @default;

protected async Task DoAsync(Func<Task> function) {
if (!Disposed)
await function.Required()().ConfigureAwait(false);
}

protected async Task<T> DoAsync<T>(Func<Task<T>> function, T @default = default) where T : struct =>
Disposed ? @default : await function.Required()().ConfigureAwait(false);
protected async Task<T?> UnsafeDoAsync<T>(Func<Task<T?>> function, T? @default = default) where T : class =>
Disposed ? @default : await function.Required()().ConfigureAwait(false);
protected async Task<T?> UnsafeDoAsync<T>(Func<Task<T?>> function) =>
Disposed ? default : await function.Required()().ConfigureAwait(continueOnCapturedContext: false);


private volatile int _disposed;

~AbstractDisposable() {
Expand Down

0 comments on commit ba414e4

Please sign in to comment.