shithub: mc

Download patch

ref: 983a758d3127bf5d861227e6a9c56900bf6e2da8
parent: ca845d8cb698f7822497046525c1ea477a944835
author: Ori Bernstein <ori@eigenstate.org>
date: Tue Oct 6 18:55:00 EDT 2015

Fix dirname/basename.

--- a/lib/std/dirname.myr
+++ b/lib/std/dirname.myr
@@ -4,6 +4,7 @@
 use "sldup.use"
 use "strfind.use"
 use "option.use"
+use "types.use"
 
 pkg std =
 	const dirname	: (p : byte[:] -> byte[:])
@@ -10,28 +11,38 @@
 	const basename	: (p : byte[:] -> byte[:])
 ;;
 
+extern const put : (fmt : byte[:], args : ... -> size)
+
 const dirname = {p
+	var end
+
+	for end = p.len; end > 1; end--
+		if p[end-1] != '/' castto(byte)
+			break
+		;;
+	;;
+	std.put("p: {}, end: {}, p[:{}]: {}\n", p, end, end, p[:end])
+	p = p[:end]
 	match std.strrfind(p, "/")
-	| `std.Some idx:
-		-> std.sldup(p[:idx])
-	| `std.None:
-		-> std.sldup(".")
+	| `std.None:	-> std.sldup(".")
+	| `std.Some 0:	-> std.sldup("/")
+	| `std.Some i:	-> std.sldup(p[:i])
 	;;
 }
 
 const basename = {p
-:again
-	if p.len == 0
-		-> std.sldup(".")
+	var end
+
+	for end = p.len; end > 1; end--
+		if p[end-1] != '/' castto(byte)
+			break
+		;;
 	;;
 
+	std.put("p: {}, end: {}, p[:{}]: {}\n", p, end, end, p[:end])
+	p = p[:end]
 	match std.strrfind(p, "/")
-	| `std.Some idx:
-		if idx == p.len - 1
-			goto again
-		;;
-		-> std.sldup(p[idx+1:])
-	| `std.None:
-		-> std.sldup(p)
+	| `std.None:	-> std.sldup(p[:end])
+	| `std.Some i:	-> std.sldup(p[i+1:end])
 	;;
 }
--- /dev/null
+++ b/lib/std/test/dirname.myr
@@ -1,0 +1,23 @@
+use std
+
+const main = {
+	eq(std.dirname("foo/bar"), "foo")
+	eq(std.dirname("/foo/bar"), "/foo")
+	eq(std.dirname("/foo/bar/"), "/foo")
+	eq(std.dirname("/bar/"), "/")
+	eq(std.dirname("/"), "/")
+	eq(std.dirname("///"), "/")
+
+	eq(std.basename("foo/bar"), "bar")
+	eq(std.basename("/foo/bar"), "bar")
+	eq(std.basename("/foo/bar/"), "bar")
+	eq(std.basename("/bar/"), "bar")
+	eq(std.basename("/"), "")
+	eq(std.basename("///"), "")
+}
+
+const eq = {a, e
+	if !std.sleq(e, a)
+		std.fatal("expected '{}', got '{}'\n", e, a)
+	;;
+}