Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use span for LengthConverter #8622

Merged
merged 5 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;

namespace MS.Internal
{
internal readonly struct PixelUnit
{
public readonly string Name;
public readonly double Factor;

private PixelUnit(string name, double factor)
{
Name = name;
Factor = factor;
}

public static bool TryParsePixel(ReadOnlySpan<char> value, out PixelUnit pixelUnit)
{
if (value.EndsWith("px", StringComparison.OrdinalIgnoreCase))
{
pixelUnit = new PixelUnit("px", 1.0);
return true;
}
else
{
pixelUnit = default;
return false;
}
}

public static bool TryParsePixelPerInch(ReadOnlySpan<char> value, out PixelUnit pixelUnit)
{
if (value.EndsWith("in", StringComparison.OrdinalIgnoreCase))
{
pixelUnit = new PixelUnit("in", 96.0);
return true;
}
else
{
pixelUnit = default;
return false;
}
}

public static bool TryParsePixelPerCentimeter(ReadOnlySpan<char> value, out PixelUnit pixelUnit)
{
if (value.EndsWith("cm", StringComparison.OrdinalIgnoreCase))
{
pixelUnit = new PixelUnit("cm", 96.0 / 2.54);
return true;
}
else
{
pixelUnit = default;
return false;
}
}

public static bool TryParsePixelPerPoint(ReadOnlySpan<char> value, out PixelUnit pixelUnit)
{
if (value.EndsWith("pt", StringComparison.OrdinalIgnoreCase))
{
pixelUnit = new PixelUnit("pt", 96.0 / 72.0);
return true;
}
else
{
pixelUnit = default;
return false;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
<Compile Include="$(WpfCommonDir)src\System\SR.cs">
<Link>Common\System\SR.cs</Link>
</Compile>
<Compile Include="$(WpfCommonDir)\src\MS\Internal\PixelUnit.cs" Link="MS\Internal\PixelUnit.cs" />
<Compile Include="$(WpfSharedDir)\MS\Internal\Xaml\Parser\SpecialBracketCharacters.cs" />
<Compile Include="$(WpfSharedDir)\RefAssemblyAttrs.cs" />
<Compile Include="$(WpfSharedDir)\MS\Internal\CommonDependencyPropertyAttribute.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,22 +196,21 @@ internal static string ConvertToString(DataGridLength length, CultureInfo cultur
/// </remarks>
private static DataGridLength ConvertFromString(string s, CultureInfo cultureInfo)
{
string goodString = s.Trim().ToLowerInvariant();
ReadOnlySpan<char> valueSpan = s.AsSpan().Trim();

// Check if the string matches any of the descriptive unit types.
// In these cases, there is no need to parse a value.
for (int i = 0; i < NumDescriptiveUnits; i++)
{
string unitString = _unitStrings[i];
if (goodString == unitString)
if (valueSpan.Equals(unitString, StringComparison.OrdinalIgnoreCase))
{
return new DataGridLength(1.0, (DataGridLengthUnitType)i);
}
}

double value = 0.0;
DataGridLengthUnitType unit = DataGridLengthUnitType.Pixel;
int strLen = goodString.Length;
int strLenUnit = 0;
double unitFactor = 1.0;

Expand All @@ -223,7 +222,7 @@ private static DataGridLength ConvertFromString(string s, CultureInfo cultureInf

// Note: This is NOT a culture specific comparison.
// This is by design: we want the same unit string table to work across all cultures.
if (goodString.EndsWith(unitString, StringComparison.Ordinal))
if (valueSpan.EndsWith(unitString, StringComparison.OrdinalIgnoreCase))
{
strLenUnit = unitString.Length;
unit = (DataGridLengthUnitType)i;
Expand All @@ -234,24 +233,18 @@ private static DataGridLength ConvertFromString(string s, CultureInfo cultureInf
// Couldn't match a standard unit type, try a non-standard unit type.
if (strLenUnit == 0)
{
numUnitStrings = _nonStandardUnitStrings.Length;
for (int i = 0; i < numUnitStrings; i++)
PixelUnit pixelUnit;
if (PixelUnit.TryParsePixelPerInch(valueSpan, out pixelUnit)
|| PixelUnit.TryParsePixelPerCentimeter(valueSpan, out pixelUnit)
|| PixelUnit.TryParsePixelPerPoint(valueSpan, out pixelUnit))
{
string unitString = _nonStandardUnitStrings[i];

// Note: This is NOT a culture specific comparison.
// This is by design: we want the same unit string table to work across all cultures.
if (goodString.EndsWith(unitString, StringComparison.Ordinal))
{
strLenUnit = unitString.Length;
unitFactor = _pixelUnitFactors[i];
break;
}
strLenUnit = pixelUnit.Name.Length;
unitFactor = pixelUnit.Factor;
}
}

// Check if there is a numerical value to parse
if (strLen == strLenUnit)
if (valueSpan.Length == strLenUnit)
{
// There is no numerical value to parse
if (unit == DataGridLengthUnitType.Star)
Expand All @@ -267,7 +260,7 @@ private static DataGridLength ConvertFromString(string s, CultureInfo cultureInf
(unit == DataGridLengthUnitType.Pixel) || DoubleUtil.AreClose(unitFactor, 1.0),
"unitFactor should not be other than 1.0 unless the unit type is Pixel.");

ReadOnlySpan<char> valueString = goodString.AsSpan(0, strLen - strLenUnit);
ReadOnlySpan<char> valueString = valueSpan.Slice(0, valueSpan.Length - strLenUnit);
value = double.Parse(valueString, provider: cultureInfo) * unitFactor;
}

Expand All @@ -276,16 +269,5 @@ private static DataGridLength ConvertFromString(string s, CultureInfo cultureInf

private static string[] _unitStrings = { "auto", "px", "sizetocells", "sizetoheader", "*" };
private const int NumDescriptiveUnits = 3;

// This array contains strings for unit types not included in the standard set
private static string[] _nonStandardUnitStrings = { "in", "cm", "pt" };

// These are conversion factors to transform other units to pixels
private static double[] _pixelUnitFactors =
{
96.0, // Pixels per Inch
96.0 / 2.54, // Pixels per Centimeter
96.0 / 72.0, // Pixels per Point
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -181,60 +181,46 @@ public override object ConvertTo(ITypeDescriptorContext typeDescriptorContext,
// NOTE - This code is called from FontSizeConverter, so changes will affect both.
static internal double FromString(string s, CultureInfo cultureInfo)
{
string valueString = s.Trim();
string goodString = valueString.ToLowerInvariant();
int strLen = goodString.Length;
int strLenUnit = 0;
ReadOnlySpan<char> valueSpan = s.AsSpan().Trim();
double unitFactor = 1.0;

//Auto is represented and Double.NaN
//properties that do not want Auto and NaN to be in their ligit values,
//should disallow NaN in validation callbacks (same goes for negative values)
if (goodString == "auto") return Double.NaN;

for (int i = 0; i < PixelUnitStrings.Length; i++)
if (valueSpan.Equals("auto", StringComparison.OrdinalIgnoreCase))
return Double.NaN;

PixelUnit pixelUnit;
if (PixelUnit.TryParsePixel(valueSpan, out pixelUnit)
|| PixelUnit.TryParsePixelPerInch(valueSpan, out pixelUnit)
|| PixelUnit.TryParsePixelPerCentimeter(valueSpan, out pixelUnit)
|| PixelUnit.TryParsePixelPerPoint(valueSpan, out pixelUnit))
{
// NOTE: This is NOT a culture specific comparison.
// This is by design: we want the same unit string table to work across all cultures.
if (goodString.EndsWith(PixelUnitStrings[i], StringComparison.Ordinal))
{
strLenUnit = PixelUnitStrings[i].Length;
unitFactor = PixelUnitFactors[i];
break;
}
valueSpan = valueSpan.Slice(0, valueSpan.Length - pixelUnit.Name.Length);
unitFactor = pixelUnit.Factor;
}

// important to substring original non-lowered string
// this allows case sensitive ToDouble below handle "NaN" and "Infinity" correctly.
// this addresses windows bug 1177408
valueString = valueString.Substring(0, strLen - strLenUnit);
if (valueSpan.IsEmpty)
return 0;

// FormatException errors thrown by Convert.ToDouble are pretty uninformative.
return ParseDouble(valueSpan, cultureInfo) * unitFactor;
}

private static double ParseDouble(ReadOnlySpan<char> span, CultureInfo cultureInfo)
{
// FormatException errors thrown by double.Parse are pretty uninformative.
// Throw a more meaningful error in this case that tells that we were attempting
// to create a Length instance from a string. This addresses windows bug 968884
try
{
double result = Convert.ToDouble(valueString, cultureInfo) * unitFactor;
return result;
return double.Parse(span, cultureInfo);
}
catch (FormatException)
{
throw new FormatException(SR.Format(SR.LengthFormatError, valueString));
throw new FormatException(SR.Format(SR.LengthFormatError, span.ToString()));
}
}

// This array contains strings for unit types
// These are effectively "TypeConverter only" units.
// They are all expressable in terms of the Pixel unit type and a conversion factor.
static private string[] PixelUnitStrings = { "px", "in", "cm", "pt" };
static private double[] PixelUnitFactors =
{
1.0, // Pixel itself
96.0, // Pixels per Inch
96.0 / 2.54, // Pixels per Centimeter
96.0 / 72.0, // Pixels per Point
};

static internal string ToString(double l, CultureInfo cultureInfo)
{
if(double.IsNaN(l)) return "Auto";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,21 +186,20 @@ static internal void FromString(
out double value,
out FigureUnitType unit)
{
string goodString = s.Trim().ToLowerInvariant();
ReadOnlySpan<char> valueSpan = s.Trim().AsSpan();

value = 0.0;
unit = FigureUnitType.Pixel;

int i;
int strLen = goodString.Length;
int strLenUnit = 0;
double unitFactor = 1.0;

// this is where we would handle trailing whitespace on the input string.
// peel [unit] off the end of the string
i = 0;

if (goodString == UnitStrings[i].Name)
if (valueSpan.Equals(UnitStrings[i].Name, StringComparison.OrdinalIgnoreCase))
{
strLenUnit = UnitStrings[i].Name.Length;
unit = UnitStrings[i].UnitType;
Expand All @@ -211,7 +210,7 @@ static internal void FromString(
{
// Note: this is NOT a culture specific comparison.
// this is by design: we want the same unit string table to work across all cultures.
if (goodString.EndsWith(UnitStrings[i].Name, StringComparison.Ordinal))
if (valueSpan.EndsWith(UnitStrings[i].Name, StringComparison.Ordinal))
{
strLenUnit = UnitStrings[i].Name.Length;
unit = UnitStrings[i].UnitType;
Expand All @@ -224,23 +223,20 @@ static internal void FromString(
// try again with a converter-only unit (a pixel equivalent).
if (i >= UnitStrings.Length)
{
for (i = 0; i < PixelUnitStrings.Length; ++i)
PixelUnit pixelUnit;
if (PixelUnit.TryParsePixelPerInch(valueSpan, out pixelUnit)
|| PixelUnit.TryParsePixelPerCentimeter(valueSpan, out pixelUnit)
|| PixelUnit.TryParsePixelPerPoint(valueSpan, out pixelUnit))
{
// Note: this is NOT a culture specific comparison.
// this is by design: we want the same unit string table to work across all cultures.
if (goodString.EndsWith(PixelUnitStrings[i], StringComparison.Ordinal))
{
strLenUnit = PixelUnitStrings[i].Length;
unitFactor = PixelUnitFactors[i];
break;
}
strLenUnit = pixelUnit.Name.Length;
unitFactor = pixelUnit.Factor;
}
}

// this is where we would handle leading whitespace on the input string.
// this is also where we would handle whitespace between [value] and [unit].
// check if we don't have a [value]. This is acceptable for certain UnitTypes.
if (strLen == strLenUnit && unit != FigureUnitType.Pixel)
if (valueSpan.Length == strLenUnit && unit != FigureUnitType.Pixel)

{
value = 1;
Expand All @@ -251,7 +247,7 @@ static internal void FromString(
Debug.Assert( unit == FigureUnitType.Pixel
|| DoubleUtil.AreClose(unitFactor, 1.0) );

ReadOnlySpan<char> valueString = goodString.AsSpan(0, strLen - strLenUnit);
ReadOnlySpan<char> valueString = valueSpan.Slice(0, valueSpan.Length - strLenUnit);
value = double.Parse(valueString, provider: cultureInfo) * unitFactor;
}
}
Expand Down Expand Up @@ -283,15 +279,6 @@ internal FigureUnitTypeStringConvert(string name, FigureUnitType unitType)
new FigureUnitTypeStringConvert("page", FigureUnitType.Page)
};

// this array contains strings for unit types that are not present in the FigureUnitType enum
static private string[] PixelUnitStrings = { "in", "cm", "pt" };
static private double[] PixelUnitFactors =
{
96.0, // Pixels per Inch
96.0 / 2.54, // Pixels per Centimeter
96.0 / 72.0, // Pixels per Point
};

#endregion Fields
}
}
Loading
Loading