using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.IO; namespace XFEToolBox.QuickTools; public static class TextActions { public static readonly string[] Actions = ["JSON 格式化", "JSON 压缩", "URL 编码", "URL 解码", "Unicode 转义", "Unicode 还原", "Base64 编码", "Base64 解码", "HTML 编码", "HTML 解码", "生成 GUID", "行去重", "去空行", "行排序", "转大写", "转小写", "SHA256"]; public static string Apply(string action, string text) { if (text.Length > 1024 * 1024) throw new ArgumentException("文本不能超过 1 MiB 字符。"); return action switch { "JSON 格式化" => Json(text, true), "JSON 压缩" => Json(text, false), "URL 编码" => Uri.EscapeDataString(text), "URL 解码" => Uri.UnescapeDataString(text), "Unicode 转义" => string.Concat(text.Select(c => c > 127 ? "\\u" + ((int)c).ToString("x4") : c.ToString())), "Unicode 还原" => Regex.Replace(text, @"\\u([0-9a-fA-F]{4})", m => ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(), RegexOptions.None, TimeSpan.FromMilliseconds(200)), "Base64 编码" => Convert.ToBase64String(Encoding.UTF8.GetBytes(text)), "Base64 解码" => new UTF8Encoding(false, true).GetString(Convert.FromBase64String(text)), "HTML 编码" => WebUtility.HtmlEncode(text), "HTML 解码" => WebUtility.HtmlDecode(text), "生成 GUID" => Guid.NewGuid().ToString(), "行去重" => string.Join(Environment.NewLine, Lines(text).Distinct(StringComparer.Ordinal)), "去空行" => string.Join(Environment.NewLine, Lines(text).Where(l => !string.IsNullOrWhiteSpace(l))), "行排序" => string.Join(Environment.NewLine, Lines(text).Order(StringComparer.Ordinal)), "转大写" => text.ToUpperInvariant(), "转小写" => text.ToLowerInvariant(), "SHA256" => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text))), _ => throw new ArgumentException("未知操作。") }; } private static string Json(string text, bool indent) { using var doc = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 64 }); return JsonSerializer.Serialize(doc.RootElement, new JsonSerializerOptions { WriteIndented = indent, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); } private static string[] Lines(string s) => s.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); public static string Match(string pattern, string text) { if (pattern.Length > 4096 || text.Length > 262144) throw new ArgumentException("正则最多 4096 字符,测试文本最多 256 KiB 字符。"); // MatchCollection.Count would enumerate every match, even after Take(200). var matches = new Regex(pattern, RegexOptions.Multiline, TimeSpan.FromMilliseconds(250)).Matches(text).Cast().Take(201).ToArray(); static string Short(string value) => value.Length > 1024 ? value[..1024] + "…(已截断)" : value; var lines = matches.Take(200).Select(m => $"[{m.Index}, {m.Length}] {Short(m.Value)}\n" + string.Join("\n", m.Groups.Cast().Skip(1).Take(32).Select((g, i) => $" 分组 {i + 1}: {Short(g.Value)}"))); return string.Join("\n", lines) + (matches.Length > 200 ? "\n仅展示前 200 项。" : $"\n共 {matches.Length} 项。"); } public static string Diff(string left, string right) { var a = Lines(left); var b = Lines(right); if (a.Length > 1500 || b.Length > 1500 || left.Length + right.Length > 524288) throw new ArgumentException("差异对比每侧最多 1500 行,总共 512 KiB 字符。"); var lcs = new ushort[a.Length + 1, b.Length + 1]; for (int i = a.Length - 1; i >= 0; i--) for (int j = b.Length - 1; j >= 0; j--) lcs[i, j] = a[i] == b[j] ? (ushort)(lcs[i + 1, j + 1] + 1) : Math.Max(lcs[i + 1, j], lcs[i, j + 1]); var output = new StringBuilder(); int x = 0, y = 0; while (x < a.Length || y < b.Length) { if (x < a.Length && y < b.Length && a[x] == b[y]) { output.AppendLine(" " + a[x++]); y++; } else if (y < b.Length && (x == a.Length || lcs[x, y + 1] >= lcs[x + 1, y])) output.AppendLine("+ " + b[y++]); else output.AppendLine("- " + a[x++]); } return output.ToString(); } public static async Task FileHashes(string path, CancellationToken token = default) { await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, true); using var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); using var md5 = IncrementalHash.CreateHash(HashAlgorithmName.MD5); byte[] buffer = new byte[65536]; int count; while ((count = await stream.ReadAsync(buffer, token)) > 0) { sha.AppendData(buffer, 0, count); md5.AppendData(buffer, 0, count); } return $"{path}\nSHA256: {Convert.ToHexStringLower(sha.GetHashAndReset())}\nMD5: {Convert.ToHexStringLower(md5.GetHashAndReset())}\nMD5 仅用于文件一致性,不用于安全校验。"; } }