shithub: mc

Download patch

ref: 83bca2aaa7635be1ef17fdd5e3b02348b79f7dcc
parent: d6095b1b433002ab661f3ebdd3bf8275f2f1925f
author: Ori Bernstein <ori@markovcorp.com>
date: Fri Jan 26 06:52:39 EST 2018

Contbuild wants strreplace.

--- a/lib/std/bld.sub
+++ b/lib/std/bld.sub
@@ -5,11 +5,11 @@
 
 	# portable files
 	alloc.myr
-	bytealloc.myr
 	assert.myr
 	bigint.myr
 	bitset.myr
 	blat.myr
+	bytealloc.myr
 	chartype.myr
 	chomp.myr
 	clear.myr
@@ -17,8 +17,8 @@
 	consts.myr
 	cstrconv.myr
 	die.myr
-	dirname.myr
 	diriter.myr
+	dirname.myr
 	endian.myr
 	errno.myr
 	execvp.myr
@@ -26,8 +26,8 @@
 	fltbits.myr
 	fltfmt.myr
 	fltparse.myr
-        fmt.myr
 	fmtfuncs.myr
+        fmt.myr
 	fndup.myr
 	getcwd.myr
 	getint.myr
@@ -51,9 +51,9 @@
 	readall.myr
 	result.myr
 	search.myr
-	sjlj.myr
 	sjlj-impl+plan9-x64.s
 	sjlj-impl+posixy-x64.s
+	sjlj.myr
 	slcp.myr
 	sldup.myr
 	sleep.myr
@@ -68,10 +68,11 @@
 	spork.myr
 	strbuf.myr
 	strfind.myr
+	striter.myr
 	strjoin.myr
+	strreplace.myr
 	strsplit.myr
 	strstrip.myr
-	striter.myr
 	swap.myr
 	threadhooks.myr
 	traits.myr
--- /dev/null
+++ b/lib/std/strreplace.myr
@@ -1,0 +1,30 @@
+use "alloc"
+use "die"
+use "slcp"
+use "strfind"
+use "sljoin"
+use "types"
+use "option"
+
+pkg std =
+	const strreplace	: (haystack : byte[:], needle : byte[:], repl : byte[:] -> byte[:])
+;;
+
+const strreplace = {haystack, needle, repl
+	var ret
+
+	iassert(needle.len > 0, "missing needle")
+	ret = ""
+	while true
+		match std.strfind(haystack, needle)
+		| `None:	break
+		| `Some idx:
+			std.sljoin(&ret, haystack[:idx])
+			std.sljoin(&ret, repl)
+			haystack = haystack[idx + needle.len:]
+		;;
+	;;
+	std.sljoin(&ret, haystack)
+	-> ret
+}
+
--- /dev/null
+++ b/lib/std/test/strreplace.myr
@@ -1,0 +1,27 @@
+use std
+use testr
+
+const main = {
+	testr.run([
+		[.name="fullstr",
+			.fn={ctx; swap(ctx, "src", "src", "dst", "dst")}],
+		[.name="head",
+			.fn={ctx; swap(ctx, "srcstuff", "src", "dst", "dststuff")}],
+		[.name="tail",
+			.fn={ctx; swap(ctx, "stuffsrc", "src", "dst", "stuffdst")}],
+		[.name="middle",
+			.fn={ctx; swap(ctx, "stusrcff", "src", "dst", "studstff")}],
+		[.name="multi",
+			.fn={ctx; swap(ctx, "srcstusrcffsrc", "src", "dst", "dststudstffdst")}],
+		[.name="overlap",
+			.fn={ctx; swap(ctx, "aaaaa", "aaa", "bbb", "bbbaa")}],
+	][:])
+}
+
+const swap = {ctx, in, src, dst, expected
+	var r
+
+	r = std.strreplace(in, src, dst)
+	testr.check(ctx, std.eq(r, expected), "got {}, expected {}\n", r, expected)
+	std.slfree(r)
+}