Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ jobs:

- name: Setup dotnet
uses: actions/setup-dotnet@v5
with:
global-json-file: global.json
dotnet-version: 10.0.x

- name: Build
shell: bash
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/publish.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ jobs:

- name: Setup dotnet
uses: actions/setup-dotnet@v5
with:
global-json-file: global.json
dotnet-version: 10.0.x

- name: Publish
shell: bash
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,24 @@ var width = UnicodeCalculator.GetWidth('コ');

// It should be 2 cells wide
Debug.Assert(width == 2);

// Strings and spans are measured per Unicode scalar,
// including emoji sequences, and return -1 if they
// contain a control character
Debug.Assert(UnicodeCalculator.GetWidth("コンニチハ") == 10);
Debug.Assert(UnicodeCalculator.GetWidth("👨‍👩‍👧".AsSpan()) == 2);
```

### Source package

The `Wcwidth.Sources` package compiles the source code into your project.
These compilation symbols change what it compiles:

* `WCWIDTH_VISIBILITY_INTERNAL` makes the types `internal` instead of `public`.
* `WCWIDTH_SYSTEM_MEMORY` adds `GetWidth(ReadOnlySpan<char>)` on targets
without a built-in `ReadOnlySpan<T>`, such as .NET Standard 2.0. Define it
when your project references the `System.Memory` package.

## Building

```
Expand Down
2 changes: 1 addition & 1 deletion build.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#:sdk Cake.Sdk@6.0.0
#:sdk Cake.Sdk@7.0.0

var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
Expand Down
2 changes: 1 addition & 1 deletion dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"rollForward": false
},
"make": {
"version": "0.9.0",
"version": "0.11.0",
"commands": [
"dotnet-make"
],
Expand Down
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "10.0.100",
"version": "11.0.100",
"rollForward": "latestFeature"
}
}
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project>
<PropertyGroup Label="Settings">
<Deterministic>true</Deterministic>
<LangVersion>14.0</LangVersion>
<LangVersion>15.0</LangVersion>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<MinVerSkip Condition="'$(Configuration)' == 'Debug'">true</MinVerSkip>
<MinVerDefaultPreReleaseIdentifiers>preview.0</MinVerDefaultPreReleaseIdentifiers>
Expand Down
21 changes: 11 additions & 10 deletions src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.0" />
<PackageVersion Include="NuGetizer" Version="1.4.5" />
<PackageVersion Include="Scriban" Version="6.5.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageVersion Include="NuGetizer" Version="1.5.1" />
<PackageVersion Include="Scriban" Version="7.6.1" />
<PackageVersion Include="Shouldly" Version="4.3.0" />
<PackageVersion Include="Spectre.Console.Cli" Version="0.53.0" />
<PackageVersion Include="Spectre.IO" Version="0.21.0" />
<PackageVersion Include="Spectre.Console.Cli" Version="0.57.2" />
<PackageVersion Include="Spectre.IO" Version="0.23.0" />
<PackageVersion Include="System.Memory" Version="4.6.3" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
<PackageVersion Include="coverlet.collector" Version="6.0.4" />
<PackageVersion Include="MinVer" Version="6.0.0" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="8.0.0" />
<PackageVersion Include="Roslynator.Analyzers" Version="4.14.1" />
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
<PackageVersion Include="coverlet.collector" Version="10.1.1" />
<PackageVersion Include="MinVer" Version="8.0.0" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="11.0.100" />
<PackageVersion Include="Roslynator.Analyzers" Version="5.0.1" />
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion src/Wcwidth.Generator/Wcwidth.Generator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>

Expand Down
2 changes: 1 addition & 1 deletion src/Wcwidth.Sources/Wcwidth.Sources.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net10.0;net9.0;net8.0;netstandard2.0</TargetFrameworks>
<TargetFrameworks>net11.0;net10.0;netstandard2.0</TargetFrameworks>
<IsPackable>true</IsPackable>
<PackBuildOutput>false</PackBuildOutput>
</PropertyGroup>
Expand Down
28 changes: 28 additions & 0 deletions src/Wcwidth.Tests.NetStandard/Wcwidth.Tests.NetStandard.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<!-- Runs the tests of Wcwidth.Tests against the netstandard2.0 build of Wcwidth -->
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<IsPackable>false</IsPackable>
<RootNamespace>Wcwidth.Tests</RootNamespace>
</PropertyGroup>

<ItemGroup>
<Compile Include="..\Wcwidth.Tests\**\*.cs" Exclude="..\Wcwidth.Tests\bin\**;..\Wcwidth.Tests\obj\**" LinkBase="Wcwidth.Tests" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk"/>
<PackageReference Include="Shouldly"/>
<PackageReference Include="xunit"/>
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Wcwidth\Wcwidth.csproj" SetTargetFramework="TargetFramework=netstandard2.0"/>
</ItemGroup>

</Project>
68 changes: 68 additions & 0 deletions src/Wcwidth.Tests/Reference/LegacyUnicodeCalculator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System.Text;

namespace Wcwidth.Tests.Reference;

/// <summary>
/// A copy of <c>UnicodeCalculator.GetWidth(string)</c> from Wcwidth 4.0.1,
/// used as the reference that the current implementation must match.
/// </summary>
public static class LegacyUnicodeCalculator
{
public static int GetWidth(string value, Unicode? version = null)
{
version ??= Unicode.Version_16_0_0;

var runes = value.EnumerateRunes().ToArray();
var end = runes.Length;

var width = 0;
var index = 0;
var lastMeasureRune = default(Rune?);
while (index < end)
{
var rune = runes[index];

if (rune.Value == '\u200D')
{
// Zero Width Joiner, do not measure this or next character
index += 2;
continue;
}

if (rune.Value == '\uFE0F' && lastMeasureRune != null)
{
// on variation selector 16 (VS16) following another character,
// conditionally add '1' to the measured width if that character is
// known to be converted from narrow to wide by the VS16 character.
if (version >= Unicode.Version_9_0_0)
{
width += Vs16Table.GetTable(Unicode.Version_9_0_0).Find(lastMeasureRune.Value.Value);
lastMeasureRune = null;
}

index++;
continue;
}

// Measure rune at current index
var wcw = UnicodeCalculator.GetWidth(rune.Value, version);
if (wcw < 0)
{
// Early return -1 on C0 and C1 control characters
return wcw;
}

if (wcw > 0)
{
// Track last character measured to contain a cell, so that
// subsequent VS-16 modifiers may be understood.
lastMeasureRune = rune;
}

width += wcw;
index++;
}

return width;
}
}
118 changes: 118 additions & 0 deletions src/Wcwidth.Tests/StringEquivalenceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
using System.Globalization;
using Wcwidth.Tests.Reference;

namespace Wcwidth.Tests;

/// <summary>
/// Compares <see cref="UnicodeCalculator.GetWidth(string, Unicode?)"/>
/// with the implementation of Wcwidth 4.0.1.
/// </summary>
public sealed class StringEquivalenceTests
{
public static TheoryData<Unicode?> Versions => [null, Unicode.Version_8_0_0, Unicode.Version_9_0_0];

private static readonly string[] _candidates = CreateCandidates();

[Theory]
[MemberData(nameof(Versions))]
public void Every_BMP_Code_Point_Should_Match_Reference(Unicode? version)
{
for (var codePoint = 0; codePoint <= char.MaxValue; codePoint++)
{
if (char.IsSurrogate((char)codePoint))
{
continue;
}

AssertMatchesReference(((char)codePoint).ToString(), version);
}
}

[Theory]
[MemberData(nameof(Versions))]
public void Every_Pair_Of_Candidates_Should_Match_Reference(Unicode? version)
{
foreach (var first in _candidates)
{
foreach (var second in _candidates)
{
AssertMatchesReference(first + second, version);
}
}
}

[Theory]
[MemberData(nameof(Versions))]
public void Random_Sequences_Of_Candidates_Should_Match_Reference(Unicode? version)
{
var random = new Random(20261118);
var builder = new System.Text.StringBuilder();
for (var i = 0; i < 20_000; i++)
{
builder.Clear();
var length = random.Next(1, 8);
for (var j = 0; j < length; j++)
{
builder.Append(_candidates[random.Next(_candidates.Length)]);
}

AssertMatchesReference(builder.ToString(), version);
}
}

private static void AssertMatchesReference(string text, Unicode? version)
{
var expected = LegacyUnicodeCalculator.GetWidth(text, version);

var actual = UnicodeCalculator.GetWidth(text, version);
if (actual != expected)
{
throw new ShouldAssertException(Describe(text, version, expected, actual, "string"));
}

var actualSpan = UnicodeCalculator.GetWidth(text.AsSpan(), version);
if (actualSpan != expected)
{
throw new ShouldAssertException(Describe(text, version, expected, actualSpan, "span"));
}
}

private static string Describe(string text, Unicode? version, int expected, int actual, string overload)
{
var codeUnits = string.Join(" ", text.Select(c => ((int)c).ToString("X4", CultureInfo.InvariantCulture)));
return $"The {overload} overload measured [{codeUnits}] (version {version?.ToString() ?? "default"}) as {actual}, but Wcwidth 4.0.1 measures {expected}.";
}

private static string[] CreateCandidates()
{
var candidates = new List<string>
{
"a", " ", "é", "中", "A", "❤", "☺", "☹", "©", "#",
"\u1100", // ᄀ Hangul Choseong Kiyeok
"\u1160", // ᅠ Hangul Jungseong Filler
"\u11A8", // ᆨ Hangul Jongseong Kiyeok
"\uAC00", // 가 Hangul Syllable Ga
"\u0007", "\n", "\t", "\u001B", "\u0085", // C0 and C1 control characters
"\uD83D", "\uDE00", // Halves of 😀: a pair when adjacent, lone surrogates otherwise
"\U0001F600", // 😀 wide emoji
"\U0001D400", // 𝐀 narrow, outside the BMP
"\U0001F1E9", "\U0001F1EA", // Regional indicators D and E
"\U0001F3FB", // Emoji modifier Fitzpatrick type 1-2
"\U000E0100", // Variation selector 17, zero width outside the BMP
};

for (var codePoint = 0; codePoint <= char.MaxValue; codePoint++)
{
var c = (char)codePoint;
var category = CharUnicodeInfo.GetUnicodeCategory(c);
if (category is UnicodeCategory.Format or UnicodeCategory.EnclosingMark
|| (codePoint >= 0xFE00 && codePoint <= 0xFE0F)
|| (category == UnicodeCategory.NonSpacingMark && codePoint < 0x0370))
{
candidates.Add(c.ToString());
}
}

return [.. candidates.Distinct()];
}
}
Loading
Loading