internal static bool TryParse(string text, ref int pos, out TUnit result) { var start = pos; if (UnitFormatCache <TUnit> .Cache.TryGetUnitForSymbol(text, ref pos, out result)) { return(true); } if (SymbolAndPowerReader.TryRead(text, ref pos, out IReadOnlyList <SymbolAndPower> symbolsAndPowers)) { var symbol = text.Substring(start, pos - start); WhiteSpaceReader.TryRead(text, ref pos, out string _); if (!IsEndOfSymbol(text, pos)) { result = Unit <TUnit> .Default; return(false); } if (UnitFormatCache <TUnit> .Cache.TryGetUnitForParts(symbolsAndPowers, out result)) { UnitFormatCache <TUnit> .Cache.Add(symbol, symbolsAndPowers); UnitFormatCache <TUnit> .Cache.Add(symbol, result); return(true); } } pos = start; result = Unit <TUnit> .Default; return(false); }
internal Caches() { var units = GetUnits(); foreach (var unit in units) { this.symbolUnitMap.Add(unit.Symbol, unit); var pos = 0; if (SymbolAndPowerReader.TryRead(unit.Symbol, ref pos, out IReadOnlyList <SymbolAndPower> result)) { if (!WhiteSpaceReader.IsRestWhiteSpace(unit.Symbol, pos)) { throw new InvalidOperationException($"Failed splitting {((IUnit)unit).Symbol} into {nameof(SymbolAndPower)}"); } if (result.Count == 0) { throw new InvalidOperationException($"Did not find any parts in {unit.Symbol}"); } this.symbolPartsMap.Add(unit.Symbol, result); var sapSet = new ReadonlySet <SymbolAndPower>(result); this.unitPartsMap.TryAdd(sapSet, unit); } } }
internal static PaddedFormat GetOrCreate(string format, ref int pos, out TUnit unit) { var start = pos; WhiteSpaceReader.TryRead(format, ref pos, out string prePadding); if (format == null || pos == format.Length) { pos = start; unit = Unit <TUnit> .Default; return(PaddedFormat.CreateUnknown(prePadding, null)); } if (Cache.TryGetUnitForSymbol(format, ref pos, out string symbol, out unit)) { if (WhiteSpaceReader.IsRestWhiteSpace(format, pos)) { WhiteSpaceReader.TryRead(format, ref pos, out string postPadding); return(new PaddedFormat(prePadding, symbol, postPadding)); } pos -= symbol.Length; } if (SymbolAndPowerReader.TryRead(format, ref pos, out IReadOnlyList <SymbolAndPower> symbolsAndPowers)) { symbol = format.Substring(start, pos - start); WhiteSpaceReader.TryRead(format, ref pos, out string postPadding); if (!WhiteSpaceReader.IsRestWhiteSpace(format, pos)) { pos = start; unit = Unit <TUnit> .Default; return(PaddedFormat.CreateUnknown(prePadding, format.Substring(start))); } if (Cache.TryGetUnitForParts(symbolsAndPowers, out unit)) { Cache.Add(symbol, symbolsAndPowers); Cache.Add(symbol, unit); } else { pos = start; unit = Unit <TUnit> .Default; return(PaddedFormat.CreateUnknown(prePadding, format.Substring(start))); } return(new PaddedFormat(prePadding, symbol, postPadding)); } pos = start; return(PaddedFormat.CreateUnknown(prePadding, format)); }