ref: 将 MeloongCore 的 WPF 部分独立到另一个子工程

This commit is contained in:
龙腾猫跃 committed 2026-04-28 21:40:00 +08:00
1 parent 1036bc9642
commit 1910e96567
13 files changed
+103 -29

No files matched your search

+236
View File
@@ -0,0 +1,236 @@
using System.Globalization;
namespace MeloongCore.Extensions;
public static class EnumerableExtensions {
#region Distinct
/// <summary>
/// 通过比较器进行去重。
/// 该方法的效率较低,建议仅在小型列表上使用,或换用 DistinctBy。
/// </summary>
public static IEnumerable<T> Distinct<T>(this IList<T> list, Func<T, T, bool> comparer) {
for (int i = 0; i < list.Count; i++) {
if (!list.Skip(i + 1).Any(item => comparer(list[i], item))) yield return list[i];
}
}
/// <summary>
/// 按对象的指定值去重。
/// </summary>
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector) {
var seen = new HashSet<TKey>();
foreach (var element in source) {
if (seen.Add(selector(element))) yield return element;
}
}
/// <summary>
/// 按对象的指定值去重。
/// </summary>
public static ParallelQuery<T> DistinctBy<T, TKey>(this ParallelQuery<T> source, Func<T, TKey> selector) {
var seen = new ConcurrentDictionary<TKey, bool>();
return source.Where(element => seen.TryAdd(selector(element), true));
}
#endregion
#region MinBy / MaxBy
/// <summary>
/// 选择所有最大值对应的对象。
/// 若没有元素则返回空列表。
/// </summary>
public static List<TKey> MaxByAll<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> {
var results = new List<TKey>();
using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return results;
TKey maxItem = enumerator.Current;
TValue maxValue = selector(maxItem);
results.Add(maxItem);
while (enumerator.MoveNext()) {
TKey currentItem = enumerator.Current;
TValue currentValue = selector(currentItem);
int comparisonResult = currentValue.CompareTo(maxValue);
if (comparisonResult > 0) {
maxValue = currentValue;
results.Clear();
results.Add(currentItem);
} else if (comparisonResult == 0) {
results.Add(currentItem);
}
}
return results;
}
/// <summary>
/// 选择所有最小值对应的对象。
/// 若没有元素则返回空列表。
/// </summary>
public static List<TKey> MinByAll<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> {
var results = new List<TKey>();
using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return results;
TKey minItem = enumerator.Current;
TValue minValue = selector(minItem);
results.Add(minItem);
while (enumerator.MoveNext()) {
TKey currentItem = enumerator.Current;
TValue currentValue = selector(currentItem);
int comparisonResult = currentValue.CompareTo(minValue);
if (comparisonResult < 0) {
minValue = currentValue;
results.Clear();
results.Add(currentItem);
} else if (comparisonResult == 0) {
results.Add(currentItem);
}
}
return results;
}
/// <summary>
/// 选择最大值对应的对象。
/// 若没有元素则返回 null。
/// </summary>
public static TKey? MaxBy<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> {
using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return default;
TKey maxItem = enumerator.Current;
TValue maxValue = selector(maxItem);
while (enumerator.MoveNext()) {
TValue value = selector(enumerator.Current);
if (value.CompareTo(maxValue) <= 0) continue;
maxItem = enumerator.Current;
maxValue = value;
}
return maxItem;
}
/// <summary>
/// 选择最小值对应的对象。
/// 若没有元素则返回 null。
/// </summary>
public static TKey? MinBy<TKey, TValue>(this IEnumerable<TKey> List, Func<TKey, TValue> Selector) where TValue : IComparable<TValue> {
using var enumerator = List.GetEnumerator();
if (!enumerator.MoveNext()) { return default; }
TKey minItem = enumerator.Current;
TValue minValue = Selector(minItem);
while (enumerator.MoveNext()) {
TValue value = Selector(enumerator.Current);
if (value.CompareTo(minValue) >= 0) { continue; }
minItem = enumerator.Current;
minValue = value;
}
return minItem;
}
#endregion
#region Join
/// <summary>
/// 用指定的分割符将集合连接为字符串。
/// </summary>
public static string Join(this IEnumerable list, char split) {
var builder = new StringBuilder();
bool isFirst = true;
foreach (var element in list) {
if (isFirst)
isFirst = false;
else
builder.Append(split);
if (element is not null) builder.Append(element.ToString());
}
return builder.ToString();
}
/// <summary>
/// 用指定的分割符将集合连接为字符串。
/// </summary>
public static string Join(this IEnumerable list, string split) {
if (split.IsSingle()) return list.Join(split[0]);
var builder = new StringBuilder();
bool isFirst = true;
foreach (var element in list) {
if (isFirst)
isFirst = false;
else
builder.Append(split);
if (element is not null) builder.Append(element.ToString());
}
return builder.ToString();
}
#endregion
#region Dictionary
/// <summary>
/// 从 <see cref="ConcurrentDictionary{TKey, TValue}"/> 中移除具有指定键的元素。
/// 返回是否确实移除了元素。
/// </summary>
public static bool Remove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key) => dict.TryRemove(key, out _);
/// <summary>
/// 将二维数组转换为字典。
/// </summary>
public static Dictionary<T, T> ToDictionary<T>(this T[,] arr) where T : notnull {
Dictionary<T, T> result = [];
if (arr.Length == 0) return result;
if (arr.GetLength(1) != 2) throw new ArgumentException("数组必须为两列,第一列为 Key,第二列为 Value。");
for (int i = 0; i < arr.GetLength(0); i++) result[arr[i, 0]] = arr[i, 1];
return result;
}
/// <summary>
/// 尝试从字典中获取某项,如果该项不存在,则返回默认值。
/// </summary>
public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default!) =>
dict.TryGetValue(key, out var result) ? result : defaultValue;
/// <summary>
/// 将值添加到字典的对应项的列表中。
/// </summary>
public static void AddIntoValueCollection<TKey, TValue>(this IDictionary<TKey, List<TValue>> dict, TKey key, TValue value) {
if (dict.TryGetValue(key, out var collection)) {
collection.Add(value);
} else {
dict.Add(key, [value]);
}
}
#endregion
/// <summary>
/// 将 <see cref="FlagsAttribute"/> 枚举值解包为它包含的单一 Flag 成员的集合。
/// 建议仅对没有极端值的正数枚举使用。
/// </summary>
/// <remarks>
/// 会跳过:0、非 2 的幂的值、不在枚举值中的数、组合值、对应同一个枚举项的多个别名。
/// </remarks>
public static IEnumerable<T> Flags<T>(this T value) where T : struct, Enum {
foreach (var element in Enum.GetValues(typeof(T)).Cast<T>().Distinct()) {
var number = Convert.ToInt64(element, CultureInfo.InvariantCulture);
if (number == 0 || (number & (number - 1)) != 0) continue; // 跳过 0 和非 2 的幂的值
if (value.HasFlag(element)) yield return element;
}
}
/// <summary>
/// 判断集合是否有且仅有一个元素。
/// 在输入 null 时返回 false。
/// </summary>
public static bool IsSingle<T>([AllowNull] this IEnumerable<T> source) {
if (source is null) return false;
if (source is IList<T> list) return list.Count == 1;
using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return false;
if (enumerator.MoveNext()) return false;
return true;
}
/// <summary>
/// 对集合的每个元素执行指定操作。
/// </summary>
public static IEnumerable<T> ForAll<T>(this IEnumerable<T> source, Action<T> action) {
foreach (T item in source) action(item);
return source;
}
}
+201
View File
@@ -0,0 +1,201 @@
using System.Text.RegularExpressions;
namespace MeloongCore.Extensions;
public static class StringExtensions {
#region 区域性 / 大小写 简化
/// <summary>
/// 高速的 StartsWith。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool StartsWithF(this string? value, string prefix, bool ignoreCase = false) {
if (value is null) return false;
return value.StartsWith(prefix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary>
/// 高速的 EndsWith。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool EndsWithF(this string? value, string suffix, bool ignoreCase = false) {
if (value is null) return false;
return value.EndsWith(suffix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary>
/// 忽略大小写的 Contains。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool ContainsIgnoreCase(this string value, string subString) {
return value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
}
/// <summary>
/// 高速的 IndexOf。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOfF(this string value, string subString, bool ignoreCase = false) {
return value.IndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary>
/// 高速的 IndexOf。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false) {
return value.IndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary>
/// 高速的 LastIndexOf。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int LastIndexOfF(this string value, string subString, bool ignoreCase = false) {
return value.LastIndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary>
/// 高速的 LastIndexOf。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int LastIndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false) {
return value.LastIndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary>
/// ToLowerInvariant 的简略写法。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string Lower(this string str) => str.ToLowerInvariant();
/// <summary>
/// ToUpperInvariant 的简略写法。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string Upper(this string str) => str.ToUpperInvariant();
#endregion
#region 分割与裁切
/// <summary>
/// 分割字符串。
/// 若原始字符串为空,则返回 {""}。
/// </summary>
public static string[] Split(this string fullStr, string splitStr) {
if (splitStr.IsSingle())
return fullStr.Split(splitStr[0]);
else
return fullStr.Split([splitStr], StringSplitOptions.None);
}
/// <summary>
/// 获取在子字符串第一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024。
/// 如果未找到子字符串则不裁切。
/// </summary>
public static string BeforeFirst(this string str, [AllowNull] string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase);
if (pos >= 0)
return str.Substring(0, pos);
else
return str;
}
/// <summary>
/// 获取在子字符串最后一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024/11。
/// 如果未找到子字符串则不裁切。
/// </summary>
public static string BeforeLast(this string str, [AllowNull] string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
if (pos >= 0)
return str.Substring(0, pos);
else
return str;
}
/// <summary>
/// 获取在子字符串第一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 11/08。
/// 如果未找到子字符串则不裁切。
/// </summary>
public static string AfterFirst(this string str, [AllowNull] string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase);
if (pos >= 0)
return str.Substring(pos + text!.Length);
else
return str;
}
/// <summary>
/// 获取在子字符串最后一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 08。
/// 如果未找到子字符串则不裁切。
/// </summary>
public static string AfterLast(this string str, [AllowNull] string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
if (pos >= 0)
return str.Substring(pos + text!.Length);
else
return str;
}
/// <summary>
/// 获取处于两个子字符串之间的部分,裁切尽可能多的内容。
/// 等效于 AfterLast 后接 BeforeFirst。
/// 如果未找到子字符串则不裁切。
/// </summary>
public static string Between(this string str, string after, string before, bool ignoreCase = false) {
int startPos = string.IsNullOrEmpty(after) ? -1 : str.LastIndexOfF(after, ignoreCase);
if (startPos >= 0)
startPos += after.Length;
else
startPos = 0;
int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase);
if (endPos >= 0)
return str.Substring(startPos, endPos - startPos);
else if (startPos > 0)
return str.Substring(startPos);
else
return str;
}
#endregion
#region 替换
/// <summary>
/// 替换字符串中的内容。
/// 仅当需要替换时,才调用 <paramref name="newValue"/> 获取结果字符串。
/// </summary>
public static string ReplaceOnDemand(this string str, string oldValue, Func<string> newValue) =>
str.Contains(oldValue) ? str.Replace(oldValue, newValue()) : str;
/// <summary>
/// 将字符串中的换行符统一替换为指定字符。
/// 若指定了 <paramref name="mergeMultiple"/>,会将多个连续换行符仅替换为一个目标内容。
/// </summary>
public static string ReplaceLineEndings(this string input, string newValue, bool mergeMultiple = false) =>
Regex.Replace(input,
mergeMultiple ? @"(?:\r\n|[\n\r\f\u0085\u2028\u2029])+" : @"\r\n|[\n\r\f\u0085\u2028\u2029]",
newValue.Replace("$", "$$"), // 避免识别成捕获组
RegexOptions.Compiled);
#endregion
/// <summary>
/// 将第一个字符转换为大写,其余字符转换为小写。
/// </summary>
public static string Capitalize(this string word) {
if (string.IsNullOrEmpty(word)) return word;
return $"{word.Substring(0, 1).Upper()}{word.Substring(1).Lower()}";
}
/// <summary>
/// 将字符串统一至某个长度。
/// 过短则用 <paramref name="code"/> 将其左侧填充,过长则截取靠左的指定长度。
/// </summary>
public static string EnsureLength(this string? str, char code, int length) {
if (str == null) str = "";
return str.Length > length ? str.Substring(0, length) : str.PadLeft(length, code);
}
/// <summary>
/// 该字符串中的字符是否均为 ASCII 字符。
/// </summary>
public static bool IsAsciiOnly(this string input) => input.All(c => c < 128);
}
+27
View File
@@ -0,0 +1,27 @@
namespace MeloongCore;
/// <summary>
/// 线程安全的 <see cref="List{T}"/> 实现。
/// 在 <see cref="SynchronizedCollection{T}"/> 的基础上,当调用枚举器时返回一个临时副本,以避免列表在枚举过程中被修改导致异常。
/// </summary>
public class ConcurrentList<T> : SynchronizedCollection<T>, IEnumerable, IEnumerable<T> {
// 构造函数
public ConcurrentList() : base() { }
public ConcurrentList(IEnumerable<T> data) : base(new object(), data) { }
public static implicit operator ConcurrentList<T>(List<T> data) => new(data);
public static implicit operator List<T>(ConcurrentList<T> data) => new(data);
// 对枚举器进行覆写,返回一个临时副本
public new IEnumerator<T> GetEnumerator() {
lock (SyncRoot) {
return Items.ToList().GetEnumerator();
}
}
IEnumerator IEnumerable.GetEnumerator() {
lock (SyncRoot) {
return Items.ToList().GetEnumerator();
}
}
}
+56
View File
@@ -0,0 +1,56 @@
namespace MeloongCore;
/// <summary>
/// 使用 Windows MsDelta API 生成、应用增量补丁文件。
/// </summary>
public static class MsDelta {
/// <summary>
/// 生成增量补丁文件:比较 <paramref name="oldFilePath"/> 和 <paramref name="newFilePath"/>,将补丁写入 <paramref name="deltaFilePath"/>。
/// </summary>
/// <exception cref="FileNotFoundException" />
/// <exception cref="Win32Exception" />
public static void Create(string oldFilePath, string newFilePath, string deltaFilePath) {
if (!File.Exists(oldFilePath)) throw new FileNotFoundException($"旧文件不存在:{oldFilePath}", oldFilePath);
if (!File.Exists(newFilePath)) throw new FileNotFoundException($"新文件不存在:{newFilePath}", newFilePath);
DirectoryUtils.Create(deltaFilePath, isFilePath: true);
// fileTypeSet:https://learn.microsoft.com/en-us/previous-versions/bb417345(v=msdn.10)?redirectedfrom=MSDN#file-type-sets (15L: DELTA_FILE_TYPE_SET_EXECUTABLES)
// 131072L: IgnoreFileSizeLimit, 32u: Crc32
if (!CreateDelta(15L, 131072L, 0L,
FileUtils.ShortenPath(oldFilePath), FileUtils.ShortenPath(newFilePath), null, null, new DeltaInput(), IntPtr.Zero, 32u, FileUtils.ShortenPath(deltaFilePath)))
throw new Win32Exception();
}
/// <summary>
/// 应用增量补丁文件:将 <paramref name="deltaFilePath"/> 补丁应用到 <paramref name="oldFilePath"/>,将结果写入 <paramref name="newFilePath"/>。
/// </summary>
/// <exception cref="FileNotFoundException" />
/// <exception cref="Win32Exception" />
public static void Apply(string oldFilePath, string deltaFilePath, string newFilePath) {
if (!File.Exists(oldFilePath)) throw new FileNotFoundException($"旧文件不存在:{oldFilePath}", oldFilePath);
if (!File.Exists(deltaFilePath)) throw new FileNotFoundException($"补丁文件不存在:{deltaFilePath}", deltaFilePath);
DirectoryUtils.Create(newFilePath, isFilePath: true);
// 1L: AllowLegacy
if (!ApplyDelta(1L, FileUtils.ShortenPath(oldFilePath), FileUtils.ShortenPath(deltaFilePath), FileUtils.ShortenPath(newFilePath)))
throw new Win32Exception();
}
[StructLayout(LayoutKind.Sequential)]
private struct DeltaInput {
public IntPtr Start;
public IntPtr Size;
[MarshalAs(UnmanagedType.Bool)] public bool Editable;
}
[DllImport("msdelta.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CreateDelta(
long fileTypeSet, long setFlags, long resetFlags,
string sourceName, string targetName, string? sourceOptionsName,
string? targetOptionsName, DeltaInput globalOptions,
IntPtr targetFileTime, uint hashAlgId, string deltaName);
[DllImport("msdelta.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ApplyDelta(long applyFlags, string sourceName, string deltaName, string targetName);
}
+94
View File
@@ -0,0 +1,94 @@
namespace MeloongCore;
public readonly struct OneOf<T0, T1> {
private readonly int _index;
private readonly T0? _value0;
private readonly T1? _value1;
public static implicit operator OneOf<T0, T1>(T0 value) => new(0, value, default);
public static implicit operator OneOf<T0, T1>(T1 value) => new(1, default, value);
private OneOf(int index, T0? value0, T1? value1) {
_index = index;
_value0 = value0;
_value1 = value1;
}
/// <summary>
/// 对不同类型执行不同的操作,并返回同一个值。
/// </summary>
public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1) => _index switch {
0 => f0(_value0!), _ => f1(_value1!)
};
/// <summary>
/// 对不同类型执行不同的操作。
/// </summary>
public void Switch(Action<T0> f0, Action<T1> f1) {
if (_index == 0) f0(_value0!);
else if (_index == 1) f1(_value1!);
}
/// <summary>
/// 判断当前的类型是否为 T。
/// </summary>
public bool Is<T>() => _index switch {
0 when typeof(T) == typeof(T0) => true,
1 when typeof(T) == typeof(T1) => true,
_ => false
};
/// <summary>
/// 假定当前的类型为 T,并返回该值。
/// 若当前值的类型不为 T,则抛出 InvalidOperationException。
/// </summary>
public T As<T>() => _index switch {
0 when typeof(T) == typeof(T0) => (T)(object)_value0!,
1 when typeof(T) == typeof(T1) => (T)(object)_value1!,
_ => throw new InvalidOperationException()
};
}
public readonly struct OneOf<T0, T1, T2> {
private readonly int _index;
private readonly T0? _value0;
private readonly T1? _value1;
private readonly T2? _value2;
public static implicit operator OneOf<T0, T1, T2>(T0 value) => new(0, value, default, default);
public static implicit operator OneOf<T0, T1, T2>(T1 value) => new(1, default, value, default);
public static implicit operator OneOf<T0, T1, T2>(T2 value) => new(2, default, default, value);
private OneOf(int index, T0? value0, T1? value1, T2? value2) {
_index = index;
_value0 = value0;
_value1 = value1;
_value2 = value2;
}
/// <summary>
/// 对不同类型执行不同的操作,并返回同一个值。
/// </summary>
public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2) => _index switch {
0 => f0(_value0!), 1 => f1(_value1!), _ => f2(_value2!)
};
/// <summary>
/// 对不同类型执行不同的操作。
/// </summary>
public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2) {
if (_index == 0) f0(_value0!);
else if (_index == 1) f1(_value1!);
else if (_index == 2) f2(_value2!);
}
/// <summary>
/// 判断当前的类型是否为 T。
/// </summary>
public bool Is<T>() => _index switch {
0 when typeof(T) == typeof(T0) => true,
1 when typeof(T) == typeof(T1) => true,
2 when typeof(T) == typeof(T2) => true,
_ => false
};
/// <summary>
/// 假定当前的类型为 T,并返回该值。
/// 若当前值的类型不为 T,则抛出 InvalidOperationException。
/// </summary>
public T As<T>() => _index switch {
0 when typeof(T) == typeof(T0) => (T) (object) _value0!,
1 when typeof(T) == typeof(T1) => (T) (object) _value1!,
2 when typeof(T) == typeof(T2) => (T) (object) _value2!,
_ => throw new InvalidOperationException()
};
}
+57
View File
@@ -0,0 +1,57 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net462</TargetFramework>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<OutDir>bin\</OutDir>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
<Configurations>Debug;Release;Snapshot</Configurations>
<Deterministic>true</Deterministic>
<LangVersion>13.0</LangVersion>
<Nullable>enable</Nullable>
<AnalysisLevel>latest-recommended</AnalysisLevel>
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Nullable" Version="1.3.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.ValueTuple" Version="4.6.1" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.ServiceModel" />
</ItemGroup>
<ItemGroup>
<Using Include="System" />
<Using Include="System.ComponentModel" />
<Using Include="System.Collections" />
<Using Include="System.Collections.Generic" />
<Using Include="System.Diagnostics.CodeAnalysis" />
<Using Include="System.Linq" />
<Using Include="System.Text" />
<Using Include="System.IO" />
<Using Include="System.Net" />
<Using Include="System.Threading" />
<Using Include="System.Collections.Concurrent" />
<Using Include="System.Runtime.CompilerServices" />
<Using Include="System.Runtime.InteropServices" />
<Using Include="MeloongCore.Extensions" />
</ItemGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>$(DefineConstants);SNAPSHOT</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Snapshot|AnyCPU'">
<Optimize>True</Optimize>
</PropertyGroup>
</Project>
+25
View File
@@ -0,0 +1,25 @@
namespace MeloongCore;
public static class DirectoryUtils {
/// <summary>
/// 确保路径以 / 或 \ 结尾。
/// </summary>
public static string ToDirectoryFormat(string folder) => IsDirectoryFormat(folder) ? folder : folder + Path.DirectorySeparatorChar;
/// <summary>
/// 检查路径是否以 / 或 \ 结尾。
/// </summary>
public static bool IsDirectoryFormat(string path) => path.EndsWithF("/") || path.EndsWithF("\\");
/// <summary>
/// 创建文件夹,或文件所在的文件夹。
/// 支持长路径。
/// 文件夹已存在时不会抛出异常。
/// </summary>
public static void Create(string path, bool isFilePath = false) {
path = FileUtils.ShortenPath(path);
if (isFilePath) path = Path.GetDirectoryName(path);
Directory.CreateDirectory(path);
}
}
+80
View File
@@ -0,0 +1,80 @@
using System.Text.RegularExpressions;
namespace MeloongCore;
public static class EscapeUtils {
/// <summary>
/// XML 转义。
/// </summary>
public static string? XmlEscape(string? str) {
if (str is null) return null;
if (str.StartsWithF("{")) str = "{}" + str; // #4187
return str
.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;")
.Replace("\"", "&quot;").ReplaceLineEndings("&#xa;");
}
/// <summary>
/// VB.NET 的 Like 关键字转义。
/// </summary>
public static string LikePatternEscape(string input) {
var builder = new StringBuilder();
foreach (char c in input) {
if (c is '[' or ']' or '*' or '?' or '#') {
builder.Append('[').Append(c).Append(']');
} else {
builder.Append(c);
}
}
return builder.ToString();
}
/// <summary>
/// 正则表达式转义。等同于 Regex.Escape。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? RegexEscape(string? value) => Regex.Escape(value);
/// <summary>
/// 正则表达式去转义。等同于 Regex.Unescape。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? RegexUnescape(string? value) => Regex.Unescape(value);
/// <summary>
/// URL 转义。等同于 Uri.EscapeDataString。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? UrlEscape(string? value) => Uri.EscapeDataString(value);
/// <summary>
/// URL 去转义。等同于 Uri.UnescapeDataString。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? UrlUnescape(string? value) => Uri.UnescapeDataString(value);
/// <summary>
/// 表单转义。等同于 WebUtility.UrlEncode。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? FormUrlEscape(string? value) => WebUtility.UrlEncode(value);
/// <summary>
/// 表单去转义。等同于 WebUtility.UrlDecode。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? FormUrlUnescape(string? value) => WebUtility.UrlDecode(value);
/// <summary>
/// HTML 转义。等同于 WebUtility.HtmlEncode。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? HtmlEscape(string? value) => WebUtility.HtmlEncode(value);
/// <summary>
/// HTML 去转义。等同于 WebUtility.HtmlDecode。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? HtmlUnescape(string? value) => WebUtility.HtmlDecode(value);
}
+78
View File
@@ -0,0 +1,78 @@
namespace MeloongCore;
public static class FileUtils {
#region 写入
/// <summary>
/// 写入文件。
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
/// </summary>
public static void Write(string filePath, string text, Encoding? encoding = null) {
DirectoryUtils.Create(filePath, isFilePath: true);
File.WriteAllText(filePath, text, encoding ?? new UTF8Encoding());
}
/// <summary>
/// 写入文件。
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
/// </summary>
public static void Write(string filePath, byte[] content) {
DirectoryUtils.Create(filePath, isFilePath: true);
File.WriteAllBytes(filePath, content);
}
/// <summary>
/// 将 <paramref name="stream" /> 写入文件。
/// 会将流的位置主动重置到开头。
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
/// </summary>
public static void Write(string filePath, Stream stream) {
DirectoryUtils.Create(filePath, isFilePath: true);
using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.Write);
if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(fileStream);
}
#endregion
#region 短路径
/// <summary>
/// 若路径较长,则尽量将其转换为短路径。
/// 若输入的是文件夹路径,不保证其结尾是否有 \ 。
/// </summary>
public static string ShortenPath(string fullName, bool keepFileName = false) {
if (string.IsNullOrEmpty(fullName) || fullName.Length <= 200) return fullName;
fullName = fullName.Replace('/', '\\');
// 保留文件名
string pathToKeep = "";
string pathToShorten = fullName;
if (fullName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
if (keepFileName && File.Exists(fullName)) {
pathToKeep = Path.GetFileName(fullName);
pathToShorten = Path.GetDirectoryName(fullName);
}
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
while (!Directory.Exists(pathToShorten) && !File.Exists(pathToShorten)) { // 如果路径不存在
string parentPath = Path.GetDirectoryName(pathToShorten);
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return fullName; // 已经到达根目录,全都不存在,直接返回
pathToKeep = Path.Combine(Path.GetFileName(pathToShorten), pathToKeep);
pathToShorten = parentPath;
}
if (pathToShorten.Length <= 10) return fullName;
// 缩短路径
char[] buffer = new char[260];
int result = GetShortPathNameW(pathToShorten, buffer, buffer.Length);
if (result == 0) return fullName;
string shortPath = new(buffer, 0, result);
return Path.Combine(shortPath, pathToKeep);
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern int GetShortPathNameW(string lpszLongPath, [Out] char[] buffer, int cchBuffer);
#endregion
}
+97
View File
@@ -0,0 +1,97 @@
using System.Numerics;
namespace MeloongCore;
public static class MathUtils {
#region 进制转换
/// <summary>
/// 将字符串作为数字,转换为指定进制的形式。
/// 进制数需在 2 到 86 之间,且输入字符串中的每个字符都必须在该进制的字符集中。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this string input, int fromRadix, int toRadix) {
const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+=!?@#$%^&*()[]{}<>;:',";
if (fromRadix < 2 || fromRadix > digits.Length) throw new ArgumentOutOfRangeException(nameof(fromRadix), $"{nameof(fromRadix)} must be between 2 and 86.");
// 零与负数的预处理
if (string.IsNullOrEmpty(input)) return "0";
bool isNegative = input.StartsWithF("-");
if (isNegative) input = input.TrimStart('-');
// 转换为十进制
BigInteger realNum = 0;
foreach (char c in input) {
int digit = digits.IndexOf(c);
if (digit == -1 || digit >= fromRadix) throw new ArgumentException($"Character '{c}' in input '{input}' is not a valid digit for radix {fromRadix}.");
realNum = realNum * fromRadix + digit;
}
return ConvertRadix(realNum * (isNegative ? -1 : 1), toRadix);
}
/// <summary>
/// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this long input, int toRadix) => ConvertRadix((BigInteger) input, toRadix);
/// <summary>
/// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this int input, int toRadix) => ConvertRadix((BigInteger) input, toRadix);
/// <summary>
/// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this byte input, int toRadix) => ConvertRadix((BigInteger) input, toRadix);
private static string ConvertRadix(this BigInteger input, int toRadix) {
const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+=!?@#$%^&*()[]{}<>;:',";
if (toRadix < 2 || toRadix > digits.Length) throw new ArgumentOutOfRangeException(nameof(toRadix), $"{nameof(toRadix)} must be between 2 and 86.");
// 零与负数的预处理
if (input == 0) return "0";
bool isNegative = input < 0;
// 转换为指定进制
var results = new List<char>();
BigInteger remaining = BigInteger.Abs(input);
BigInteger bigRadix = toRadix;
while (remaining > 0) {
remaining = BigInteger.DivRem(remaining, bigRadix, out BigInteger remainder);
results.Add(digits[(int) remainder]);
}
// 负数的结束处理与返回
if (isNegative) results.Add('-');
results.Reverse();
return new([..results]);
}
#endregion
/// <summary>
/// 将值限制在指定范围内。
/// </summary>
public static T Clamp<T>(this T value, T min, T max) where T : IComparable<T> {
if (value.CompareTo(min) < 0) return min;
if (value.CompareTo(max) > 0) return max;
return value;
}
/// <summary>
/// 在一个范围中进行线性插值。
/// 返回值将被舍入到小数点后 7 位,以解决浮点数误差问题。
/// </summary>
public static double Lerp(double start, double end, double percentage) =>
Math.Round(start + (end - start) * percentage, 7);
/// <summary>
/// 计算二阶贝塞尔曲线。
/// </summary>
public static double Bezier(double t, double x1, double y1, double x2, double y2, double accuracy = 0.01) {
if (t < 0.0000001 || double.IsNaN(t)) return 0;
if (t > 0.9999999) return 1;
double a = t;
double b;
do {
b = 3 * a * ((0.33333333 + x1 - x2) * a * a + (x2 - 2 * x1) * a + x1);
a += (t - b) * 0.5;
} while (!(Math.Abs(b - t) < accuracy)); // 精度
return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1);
}
}