internal static bool TryParse(string?format, [MaybeNullWhen(false)] out QuantityFormat <TUnit> result) { if (string.IsNullOrWhiteSpace(format)) { result = QuantityFormat <TUnit> .CreateUnknown("{nameof(format) is null}", Unit <TUnit> .Default); return(false); } if (Cache.TryGetValue(format, out result)) { return(true); } var pos = 0; _ = WhiteSpaceReader.TryRead(format, ref pos); var end = format.Length; if (TryReadPrefix(format, ref pos)) { end = format.LastIndexOf('}'); if (end < 0) { result = QuantityFormat <TUnit> .CreateUnknown(format, Unit <TUnit> .Default); return(false); } if (!WhiteSpaceReader.IsRestWhiteSpace(format, end + 1)) { result = QuantityFormat <TUnit> .CreateUnknown(format, Unit <TUnit> .Default); return(false); } } var trimmedFormat = pos != end ? format.Substring(pos, end - pos) : format; var success = CompositeFormatParser.TryParse(trimmedFormat, out result); if (success) { Cache.Add(format, result); } return(success); }
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var text = value as string; if (string.IsNullOrWhiteSpace(text)) { return(null); } var settings = Settings.Instance; var pos = 0; _ = WhiteSpaceReader.TryRead(text, ref pos); var indexOf = text.IndexOf("1/", pos, StringComparison.Ordinal); if (indexOf >= 0) { pos = indexOf + 2; } if (SymbolAndPowerReader.TryRead(text, ref pos, out IReadOnlyList <SymbolAndPower> result)) { if (WhiteSpaceReader.IsRestWhiteSpace(text, pos)) { var unitAndPowers = result.Select(sap => UnitAndPower.Create(settings.AllUnits.Single(x => x.Symbol == sap.Symbol), sap.Power)) .ToList(); var unitParts = new UnitParts(unitAndPowers); if (indexOf < 0) { return(unitParts); } return(unitParts.Inverse()); } } return(text); }
internal static PaddedFormat GetOrCreate(string?format) { if (string.IsNullOrEmpty(format)) { return(PaddedFormat.NullFormat); } if (Cache.TryGet(format, out var match)) { return(match); } var pos = 0; var paddedFormat = GetOrCreate(format, ref pos); if (!WhiteSpaceReader.IsRestWhiteSpace(format, pos)) { paddedFormat = paddedFormat.AsUnknownFormat(); } _ = Cache.Add(format, paddedFormat); return(paddedFormat); }