diff --git a/OpenMcdf3/DirectoryEntryComparer.cs b/OpenMcdf3/DirectoryEntryComparer.cs new file mode 100644 index 00000000..e68c6374 --- /dev/null +++ b/OpenMcdf3/DirectoryEntryComparer.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; +using System.Text; + +namespace OpenMcdf3; + +internal class DirectoryEntryComparer : IComparer +{ + public static DirectoryEntryComparer Default { get; } = new(); + + public int Compare(DirectoryEntry? x, DirectoryEntry? y) + { + Debug.Assert(x is not null && y is not null); + + if (x == null && y == null) + return 0; + + if (x is null) + return -1; + + if (y is null) + return 1; + + int xLength = Encoding.Unicode.GetByteCount(x.Name); + int yLength = Encoding.Unicode.GetByteCount(y.Name); + + if (xLength < y.Name.Length) + return -1; + + if (yLength > xLength) + return 1; + + for (int i = 0; i < x.Name.Length; i++) + { + char xChar = char.ToUpperInvariant(x.Name[i]); + char yChar = char.ToUpperInvariant(y.Name[i]); + + if (xChar < yChar) + return -1; + if (yChar > xChar) + return 1; + } + + return 0; + } +}