From da467a10b01c1c465ed312711c2498910ef15571 Mon Sep 17 00:00:00 2001 From: Alex Barney Date: Tue, 7 Jan 2020 22:51:59 -0700 Subject: [PATCH] Add ToU8String method to U8Span. Add PathTools.GetFileName --- src/LibHac/Common/U8Span.cs | 5 +++++ src/LibHac/Common/U8SpanMutable.cs | 5 +++++ src/LibHac/FsSystem/PathTools.cs | 16 ++++++++++++++++ tests/LibHac.Tests/PathToolsTests.cs | 24 ++++++++++++++++++++++++ 4 files changed, 50 insertions(+) diff --git a/src/LibHac/Common/U8Span.cs b/src/LibHac/Common/U8Span.cs index e36ad0c4..3e46ab0d 100644 --- a/src/LibHac/Common/U8Span.cs +++ b/src/LibHac/Common/U8Span.cs @@ -47,6 +47,11 @@ namespace LibHac.Common return StringUtils.Utf8ZToString(_buffer); } + public U8String ToU8String() + { + return new U8String(_buffer.ToArray()); + } + public bool IsNull() => _buffer == default; } } diff --git a/src/LibHac/Common/U8SpanMutable.cs b/src/LibHac/Common/U8SpanMutable.cs index 3570d7ab..c89d5c34 100644 --- a/src/LibHac/Common/U8SpanMutable.cs +++ b/src/LibHac/Common/U8SpanMutable.cs @@ -51,6 +51,11 @@ namespace LibHac.Common return StringUtils.Utf8ZToString(_buffer); } + public U8StringMutable ToU8String() + { + return new U8StringMutable(_buffer.ToArray()); + } + public bool IsNull() => _buffer == default; } } diff --git a/src/LibHac/FsSystem/PathTools.cs b/src/LibHac/FsSystem/PathTools.cs index 837a8e57..3b689de7 100644 --- a/src/LibHac/FsSystem/PathTools.cs +++ b/src/LibHac/FsSystem/PathTools.cs @@ -246,6 +246,22 @@ namespace LibHac.FsSystem return path.Slice(0, i); } + /// + /// Returns the name and extension parts of the given path. The returned ReadOnlySpan + /// contains the characters of the path that follows the last separator in path. + /// + public static ReadOnlySpan GetFileName(ReadOnlySpan path) + { + Debug.Assert(IsNormalized(path)); + + int i = path.Length; + + while (i >= 1 && path[i - 1] != '/') i--; + + i = Math.Max(i, 0); + return path.Slice(i, path.Length - i); + } + public static bool IsNormalized(ReadOnlySpan path) { var state = NormalizeState.Initial; diff --git a/tests/LibHac.Tests/PathToolsTests.cs b/tests/LibHac.Tests/PathToolsTests.cs index 1435c0a2..e4450321 100644 --- a/tests/LibHac.Tests/PathToolsTests.cs +++ b/tests/LibHac.Tests/PathToolsTests.cs @@ -275,5 +275,29 @@ namespace LibHac.Tests Assert.Equal(Math.Max(0, destSize - 1), normalizedLength); Assert.Equal(expected, actual); } + + public static object[][] GetFileNameTestItems = + { + new object[] {"/a/bb/ccc", "ccc"}, + new object[] {"/a/bb/ccc/", ""}, + new object[] {"/a/bb", "bb"}, + new object[] {"/a/bb/", ""}, + new object[] {"/a", "a"}, + new object[] {"/a/", ""}, + new object[] {"/", ""}, + }; + + [Theory] + [MemberData(nameof(GetFileNameTestItems))] + public static void GetFileNameTest(string path, string expected) + { + var u8Path = path.ToU8String(); + + ReadOnlySpan fileName = PathTools.GetFileName(u8Path); + + string actual = StringUtils.Utf8ZToString(fileName); + + Assert.Equal(expected, actual); + } } }