Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
TheArcaneBrony committed Dec 14, 2023
1 parent 788516b commit 28c0e5a
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 38 deletions.
2 changes: 0 additions & 2 deletions ArcaneLibs/Collections/AutoPopulatingDictionary.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System.Diagnostics.CodeAnalysis;

namespace ArcaneLibs.Collections;

public class AutoPopulatingDictionary<T1, T2> : Dictionary<T1, T2> where T1 : notnull {
Expand Down
2 changes: 2 additions & 0 deletions ArcaneLibs/Extensions/BooleanExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
namespace ArcaneLibs.Extensions;

public static class BooleanExtensions {
#pragma warning disable CS0665 // Assignment in conditional expression is always constant
public static string Toggle(this ref bool @bool) => (@bool ^= true) ? "enabled" : "disabled";
#pragma warning restore CS0665 // Assignment in conditional expression is always constant

public static (bool, string) ToggleAlt(this bool @bool) => (@bool ^= true, @bool ? "enabled" : "disabled");

Expand Down
23 changes: 14 additions & 9 deletions ArcaneLibs/Extensions/ObjectExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.Encodings.Web;
Expand All @@ -11,17 +10,21 @@ namespace ArcaneLibs.Extensions;
public static class ObjectExtensions {
public static void SaveToJsonFile(this object? @object, string filename) => File.WriteAllText(filename, ToJson(@object));

private static readonly JsonSerializerOptions ToJsonSerializerOptions = new JsonSerializerOptions();
private static readonly Dictionary<byte, JsonSerializerOptions> OptionsCache = new();

public static string ToJson(this object? obj, bool indent = true, bool ignoreNull = false, bool unsafeContent = false) {
if (obj is null) return "";
ToJsonSerializerOptions.WriteIndented = indent;
ToJsonSerializerOptions.DefaultIgnoreCondition = ignoreNull ? JsonIgnoreCondition.WhenWritingNull : JsonIgnoreCondition.Never;
ToJsonSerializerOptions.Encoder = unsafeContent ? JavaScriptEncoder.UnsafeRelaxedJsonEscaping : null;
return JsonSerializer.Serialize(obj, obj.GetType(), ToJsonSerializerOptions);
var cacheKey = (byte)((indent ? 1 : 0) | (ignoreNull ? 2 : 0) | (unsafeContent ? 4 : 0));
var options = OptionsCache.GetOrCreate(cacheKey , _ => new JsonSerializerOptions {
WriteIndented = indent,
DefaultIgnoreCondition = ignoreNull ? JsonIgnoreCondition.WhenWritingNull : JsonIgnoreCondition.Never,
Encoder = unsafeContent ? JavaScriptEncoder.UnsafeRelaxedJsonEscaping : null
});
return JsonSerializer.Serialize(obj, obj.GetType(), options);

Check warning on line 23 in ArcaneLibs/Extensions/ObjectExtensions.cs

View workflow job for this annotation

GitHub Actions / build

Using member 'System.Text.Json.JsonSerializer.Serialize(Object, Type, JsonSerializerOptions)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.
}

public static T? DeepClone<T>(this T? obj) where T : class {
Console.WriteLine($"DeepClone<{typeof(T)}>");
if (obj is null) return null;
var type = typeof(T);
if (type.IsValueType || type == typeof(string)) return obj;
Expand All @@ -44,7 +47,9 @@ public static string ToJson(this object? obj, bool indent = true, bool ignoreNul
foreach (var field in fields) {
var fieldValue = field.GetValue(obj);
if (fieldValue == null) continue;
field.SetValue(instance, DeepClone(fieldValue));
var newValue = DeepClone(fieldValue);
Console.WriteLine($"{field.Name}: {fieldValue.GetType().Name} -> {newValue.GetType().Name}");

Check warning on line 51 in ArcaneLibs/Extensions/ObjectExtensions.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 51 in ArcaneLibs/Extensions/ObjectExtensions.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 51 in ArcaneLibs/Extensions/ObjectExtensions.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 51 in ArcaneLibs/Extensions/ObjectExtensions.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
field.SetValue(instance, newValue);
}

return instance;
Expand All @@ -58,7 +63,7 @@ public static (T? left, T? right) FindDifferencesDeep<T>(this T? left, T? right)
if (left is null && right is not null) return (null, right);
if (left is not null && right is null) return (left, null);
if (left is null && right is null) return (null, null);

var type = typeof(T);
if (type.IsValueType || type == typeof(string)) return (left, right);
if (type.IsArray) {
Expand Down Expand Up @@ -95,7 +100,7 @@ public static (T? left, T? right) FindDifferencesDeep<T>(this T? left, T? right)
field.SetValue(instanceRight, fieldValueRight);
}

return ((T)instanceLeft, (T)instanceRight);
return (instanceLeft, instanceRight);
}

throw new ArgumentException($"Unknown type: {type}");
Expand Down
6 changes: 3 additions & 3 deletions ArcaneLibs/Extensions/Streams/StreamExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace ArcaneLibs.Extensions.Streams;

[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
public static class StreamExtensions {
private const bool _debug = false;
// private const bool _debug = false;

public static long Remaining(this Stream stream) =>
//if (_debug) if (_debug) Console.WriteLine($"stream pos: {stream.Position}, stream len: {stream.Length}, stream rem: {stream.Length - stream.Position}");
Expand Down Expand Up @@ -95,7 +95,7 @@ public static bool StartsWith(this Stream stream, IEnumerable<byte> sequence) {
return true;
}

public static bool StartsWith(this Stream stream, string ascii_seq) => stream.StartsWith(ascii_seq.Select(x => (byte)x));
public static bool StartsWith(this Stream stream, string asciiSeq) => stream.StartsWith(asciiSeq.Select(x => (byte)x));

public static Stream Skip(this Stream stream, long count = 1) {
if (!stream.CanSeek)
Expand Down Expand Up @@ -181,7 +181,7 @@ public static IEnumerable<byte> ReadToEnd(this Stream stream) {
if (!stream.CanRead)
throw new InvalidOperationException("Can't read a non-readable stream");

var read = 0;
int read;
while ((read = stream.ReadByte()) != -1)
yield return (byte)read;
}
Expand Down
48 changes: 24 additions & 24 deletions ArcaneLibs/Util.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,30 +51,30 @@ public static void DirectoryCopy(string sourceDirName, string destDirName, bool
}
}

public static void DownloadFile(string contextName, string url, string filename, bool overwrite = false, bool extract = false, bool printProgress = true) {
using var wc = new WebClient();
if (File.Exists(filename) && !overwrite) {
Console.WriteLine($"Not downloading {filename}, file exists.");
return;
}

if (File.Exists(filename)) File.Delete(filename);

if (printProgress)
wc.DownloadProgressChanged += (_, args) => { Console.Write($"Downloading {contextName}... {args.ProgressPercentage}%\r"); };
wc.DownloadFileCompleted += (_, _) => {
//Console.WriteLine(printProgress?"\n":"" + $"Finished downloading {contextName}");
};
wc.DownloadFileTaskAsync(new Uri(url), filename).Wait();
Console.WriteLine($"Downloading {contextName}... [DONE]");
if (extract) {
Console.WriteLine($"Extracting {contextName}...");
ZipFile.ExtractToDirectory(filename, contextName, overwrite);
File.Delete(filename);
}

while (wc.IsBusy) Thread.Sleep(1000);
}
// public static void DownloadFile(string contextName, string url, string filename, bool overwrite = false, bool extract = false, bool printProgress = true) {
// using var wc = new WebClient();
// if (File.Exists(filename) && !overwrite) {
// Console.WriteLine($"Not downloading {filename}, file exists.");
// return;
// }
//
// if (File.Exists(filename)) File.Delete(filename);
//
// if (printProgress)
// wc.DownloadProgressChanged += (_, args) => { Console.Write($"Downloading {contextName}... {args.ProgressPercentage}%\r"); };
// wc.DownloadFileCompleted += (_, _) => {
// //Console.WriteLine(printProgress?"\n":"" + $"Finished downloading {contextName}");
// };
// wc.DownloadFileTaskAsync(new Uri(url), filename).Wait();
// Console.WriteLine($"Downloading {contextName}... [DONE]");
// if (extract) {
// Console.WriteLine($"Extracting {contextName}...");
// ZipFile.ExtractToDirectory(filename, contextName, overwrite);
// File.Delete(filename);
// }
//
// while (wc.IsBusy) Thread.Sleep(1000);
// }

public static int Min(params int[] numbers) => numbers.Min();

Expand Down

0 comments on commit 28c0e5a

Please sign in to comment.