Add ToU8String method to U8Span. Add PathTools.GetFileName

This commit is contained in:
Alex Barney 2020-01-07 22:51:59 -07:00
parent b742a37012
commit da467a10b0
4 changed files with 50 additions and 0 deletions

View file

@ -47,6 +47,11 @@ namespace LibHac.Common
return StringUtils.Utf8ZToString(_buffer);
}
public U8String ToU8String()
{
return new U8String(_buffer.ToArray());
}
public bool IsNull() => _buffer == default;
}
}

View file

@ -51,6 +51,11 @@ namespace LibHac.Common
return StringUtils.Utf8ZToString(_buffer);
}
public U8StringMutable ToU8String()
{
return new U8StringMutable(_buffer.ToArray());
}
public bool IsNull() => _buffer == default;
}
}

View file

@ -246,6 +246,22 @@ namespace LibHac.FsSystem
return path.Slice(0, i);
}
/// <summary>
/// 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.
/// </summary>
public static ReadOnlySpan<byte> GetFileName(ReadOnlySpan<byte> 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<char> path)
{
var state = NormalizeState.Initial;

View file

@ -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<byte> fileName = PathTools.GetFileName(u8Path);
string actual = StringUtils.Utf8ZToString(fileName);
Assert.Equal(expected, actual);
}
}
}