XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Globalization;
using System.Numerics;
using System.Text.RegularExpressions;

namespace XFEToolBox.QuickTools;

/// <summary>Bounded expression grammar, never evaluates C#, PowerShell or shell input.</summary>
public static class Calculator
{
    private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
    public static string Calculate(string text)
    {
        if (text.Length > 2048) throw new FormatException("表达式最多 2048 个字符。");
        text = text.Trim().TrimStart('=').Trim();
        if (text.Length == 0) throw new FormatException("请输入表达式,例如 1920/1080 或 sqrt(256)。");
        var parser = new Parser(text); double value = parser.Expression(); parser.Finish();
        if (!double.IsFinite(value)) throw new FormatException("结果超出范围或运算无定义。");
        return value.ToString("G15", Inv);
    }
    public static string ConvertUnit(string input)
    {
        var match = Regex.Match(input.Trim(), @"^([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?)\s*([a-zA-Z°]+)\s+(?:to|到)\s*([a-zA-Z°]+)$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100));
        if (!match.Success) throw new FormatException("格式示例:10 ft to m、1 GiB to MiB、32 F to C。GB 使用十进制,GiB 使用二进制。");
        double n = double.Parse(match.Groups[1].Value, Inv); string from = match.Groups[2].Value.ToLowerInvariant().TrimStart('°'), to = match.Groups[3].Value.ToLowerInvariant().TrimStart('°');
        double result;
        if (new[] { "c", "f", "k" }.Contains(from) && new[] { "c", "f", "k" }.Contains(to))
        {
            double kelvin = from == "c" ? n + 273.15 : from == "f" ? (n - 32) * 5 / 9 + 273.15 : n;
            if (kelvin < -1e-10) throw new FormatException("温度不能低于绝对零度。");
            result = to == "c" ? kelvin - 273.15 : to == "f" ? (kelvin - 273.15) * 9 / 5 + 32 : kelvin;
        }
        else
        {
            if (!Units.TryGetValue(from, out var a) || !Units.TryGetValue(to, out var b) || a.Dimension != b.Dimension) throw new FormatException("单位未知或维度不一致。");
            result = n * a.Factor / b.Factor;
        }
        if (!double.IsFinite(result)) throw new FormatException("换算结果超出范围。");
        return result.ToString("G15", Inv) + " " + match.Groups[3].Value;
    }
    private static readonly Dictionary<string, (string Dimension, double Factor)> Units = new()
    {
        ["mm"] = ("length", .001),
        ["cm"] = ("length", .01),
        ["m"] = ("length", 1),
        ["km"] = ("length", 1000),
        ["in"] = ("length", .0254),
        ["ft"] = ("length", .3048),
        ["yd"] = ("length", .9144),
        ["mi"] = ("length", 1609.344),
        ["b"] = ("bytes", 1),
        ["kb"] = ("bytes", 1000),
        ["mb"] = ("bytes", 1e6),
        ["gb"] = ("bytes", 1e9),
        ["tb"] = ("bytes", 1e12),
        ["kib"] = ("bytes", 1024),
        ["mib"] = ("bytes", 1048576),
        ["gib"] = ("bytes", 1073741824),
        ["tib"] = ("bytes", 1099511627776),
        ["ms"] = ("time", .001),
        ["s"] = ("time", 1),
        ["min"] = ("time", 60),
        ["h"] = ("time", 3600),
        ["day"] = ("time", 86400),
        ["g"] = ("mass", .001),
        ["kg"] = ("mass", 1),
        ["lb"] = ("mass", .45359237)
    };
    public static string ConvertBase(string text, int from, int to)
    {
        if (from is < 2 or > 36 || to is < 2 or > 36 || text.Length is 0 or > 512) throw new FormatException("支持 2–36 进制,最多 512 位。");
        string s = text.Trim().ToLowerInvariant(); bool negative = s.StartsWith('-'); if (negative) s = s[1..];
        if (s.Length == 0) throw new FormatException("请输入整数。");
        BigInteger n = 0;
        foreach (char ch in s) { int v = "0123456789abcdefghijklmnopqrstuvwxyz".IndexOf(ch); if (v < 0 || v >= from) throw new FormatException("数字不属于所选进制。"); n = n * from + v; }
        if (n.IsZero) return "0";
        string output = ""; while (n > 0) { n = BigInteger.DivRem(n, to, out var rem); output = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[(int)rem] + output; }
        return (negative ? "-" : "") + output;
    }
    public static string Timestamp(string input)
    {
        input = input.Trim();
        if (long.TryParse(input, out long timestamp))
        {
            var date = Math.Abs((double)timestamp) >= 100000000000 ? DateTimeOffset.FromUnixTimeMilliseconds(timestamp) : DateTimeOffset.FromUnixTimeSeconds(timestamp);
            return $"UTC {date:yyyy-MM-dd HH:mm:ss.fff zzz}\n本地 {date.ToLocalTime():yyyy-MM-dd HH:mm:ss.fff zzz}";
        }
        var instant = DateTimeOffset.Parse(input, Inv, DateTimeStyles.AllowWhiteSpaces);
        return $"秒:{instant.ToUnixTimeSeconds()}\n毫秒:{instant.ToUnixTimeMilliseconds()}";
    }
    public static string DateDifference(string first, string second)
    {
        var duration = DateTimeOffset.Parse(second, Inv) - DateTimeOffset.Parse(first, Inv);
        return $"{duration.TotalDays:G12} 天\n{duration.TotalHours:G12} 小时\n{duration.TotalSeconds:G15} 秒";
    }
    private sealed class Parser(string text)
    {
        private int at, depth;
        private void Space() { while (at < text.Length && char.IsWhiteSpace(text[at])) at++; }
        private bool Eat(char c) { Space(); if (at == text.Length || text[at] != c) return false; at++; return true; }
        public void Finish() { Space(); if (at != text.Length) throw new FormatException($"第 {at + 1} 位存在无法识别的内容。"); }
        public double Expression()
        {
            if (++depth > 64) throw new FormatException("括号嵌套过深。");
            try { double n = Term(); while (true) { if (Eat('+')) n += Term(); else if (Eat('-')) n -= Term(); else return n; } }
            finally { depth--; }
        }
        private double Term() { double n = Unary(); while (true) { if (Eat('*') || Eat('×')) n *= Unary(); else if (Eat('/') || Eat('÷')) { double d = Unary(); if (d == 0) throw new FormatException("不能除以零。"); n /= d; } else if (Eat('%')) { double d = Unary(); if (d == 0) throw new FormatException("不能对零取余。"); n %= d; } else return n; } }
        private double Unary()
        {
            if (++depth > 64) throw new FormatException("表达式嵌套过深。");
            try { if (Eat('+')) return Unary(); if (Eat('-')) return -Unary(); double n = Atom(); return Eat('^') ? Math.Pow(n, Unary()) : n; }
            finally { depth--; }
        }
        private double Atom()
        {
            if (Eat('(')) { double n = Expression(); if (!Eat(')')) throw new FormatException("缺少右括号。"); return n; }
            Space(); int start = at;
            if (at < text.Length && char.IsLetter(text[at]))
            {
                while (at < text.Length && char.IsLetter(text[at])) at++; string id = text[start..at].ToLowerInvariant();
                if (id == "pi") return Math.PI; if (id == "e") return Math.E;
                if (!Eat('(')) throw new FormatException("函数需要括号。"); double n = Expression(); if (!Eat(')')) throw new FormatException("缺少右括号。");
                return id switch { "sqrt" => Math.Sqrt(n), "abs" => Math.Abs(n), "sin" => Math.Sin(n), "cos" => Math.Cos(n), "tan" => Math.Tan(n), "ln" => Math.Log(n), "log" => Math.Log10(n), "floor" => Math.Floor(n), "ceil" => Math.Ceiling(n), "round" => Math.Round(n), _ => throw new FormatException("未知函数。三角函数使用弧度。") };
            }
            while (at < text.Length && (char.IsDigit(text[at]) || text[at] == '.')) at++;
            if (at < text.Length && text[at] is 'e' or 'E') { at++; if (at < text.Length && text[at] is '+' or '-') at++; while (at < text.Length && char.IsDigit(text[at])) at++; }
            if (!double.TryParse(text[start..at], NumberStyles.Float, Inv, out double value)) throw new FormatException($"第 {start + 1} 位应为数字。"); return value;
        }
    }
}