From 795f4f86d8653d532caff381b11375170af8ffa0 Mon Sep 17 00:00:00 2001 From: Jeremy Powell Date: Thu, 7 Nov 2024 10:19:24 +1300 Subject: [PATCH] Add DirectoryEntryComparer --- OpenMcdf3/DirectoryEntryComparer.cs | 45 +++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 OpenMcdf3/DirectoryEntryComparer.cs 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; + } +}