authorgravatar for r00ster91@proton.meWooster <r00ster91@proton.me> 2022-10-23 18:58:24+02:00
committergravatar for r00ster91@proton.meWooster <r00ster91@proton.me> 2022-10-24 18:06:40+02:00
log7721c0cbef36bc785a003d7d183ff662e4837c13
tree51a45fb23c9305fb03562679bd8a8267a1d62491
parenta0a50955f080bd5576ef43cd8b56466d0d4cbd20

std.fs.path: add stem()


1 files changed, 37 insertions(+), 0 deletions(-)

lib/std/fs/path.zig+37
......@@ -1319,3 +1319,40 @@ test "extension" {
13191319 try testExtension("/foo/bar/bam/a.b.c", ".c");
13201320 try testExtension("/foo/bar/bam/a.b.c/", ".c");
13211321}
1322
1323/// Returns the last component of this path without its extension (if any):
1324/// - "hello/world/lib.tar.gz" ⇒ "lib.tar"
1325/// - "hello/world/lib.tar" ⇒ "lib"
1326/// - "hello/world/lib" ⇒ "lib"
1327pub fn stem(path: []const u8) []const u8 {
1328 const filename = basename(path);
1329 const index = mem.lastIndexOfScalar(u8, filename, '.') orelse return filename[0..];
1330 if (index == 0) return path;
1331 return filename[0..index];
1332}
1333
1334fn testStem(path: []const u8, expected: []const u8) !void {
1335 try testing.expectEqualStrings(expected, stem(path));
1336}
1337
1338test "stem" {
1339 try testStem("hello/world/lib.tar.gz", "lib.tar");
1340 try testStem("hello/world/lib.tar", "lib");
1341 try testStem("hello/world/lib", "lib");
1342 try testStem("hello/lib/", "lib");
1343 try testStem("hello...", "hello..");
1344 try testStem("hello.", "hello");
1345 try testStem("/hello.", "hello");
1346 try testStem(".gitignore", ".gitignore");
1347 try testStem(".image.png", ".image");
1348 try testStem("file.ext", "file");
1349 try testStem("file.ext.", "file.ext");
1350 try testStem("a.b.c", "a.b");
1351 try testStem("a.b.c/", "a.b");
1352 try testStem(".a", ".a");
1353 try testStem("///", "");
1354 try testStem("..", ".");
1355 try testStem(".", ".");
1356 try testStem(" ", " ");
1357 try testStem("", "");
1358}