diff --git a/src/core/string.c b/src/core/string.c index 94df1417..db75e56a 100644 --- a/src/core/string.c +++ b/src/core/string.c @@ -274,6 +274,28 @@ static Janet cfun_string_find(int32_t argc, Janet *argv) { : janet_wrap_integer(result); } +static Janet cfun_string_hasprefix(int32_t argc, Janet *argv) { + janet_fixarity(argc, 2); + const uint8_t *prefix = janet_getstring(argv, 0); + const uint8_t *s = janet_getstring(argv, 1); + int32_t prefix_len = janet_string_length(prefix); + int32_t s_len = janet_string_length(s); + return s_len < prefix_len + ? janet_wrap_false() + : janet_wrap_boolean(memcmp(prefix, s, prefix_len) == 0); +} + +static Janet cfun_string_hassuffix(int32_t argc, Janet *argv) { + janet_fixarity(argc, 2); + const uint8_t *suffix = janet_getstring(argv, 0); + const uint8_t *s = janet_getstring(argv, 1); + int32_t suffix_len = janet_string_length(suffix); + int32_t s_len = janet_string_length(s); + return s_len < suffix_len + ? janet_wrap_false() + : janet_wrap_boolean(memcmp(suffix, s+s_len-suffix_len, suffix_len) == 0); +} + static Janet cfun_string_findall(int32_t argc, Janet *argv) { int32_t result; struct kmp_state state; @@ -507,6 +529,16 @@ static const JanetReg string_cfuns[] = { "will only contribute to finding at most on occurrence of pattern. If no " "occurrences are found, will return an empty array.") }, + { + "string/has-prefix?", cfun_string_hasprefix, + JDOC("(string/has-prefix? pfx str)\n\n" + "Tests whether str starts with pfx.") + }, + { + "string/has-suffix?", cfun_string_hassuffix, + JDOC("(string/has-suffix? sfx str)\n\n" + "Tests whether str ends with sfx.") + }, { "string/replace", cfun_string_replace, JDOC("(string/replace patt subst str)\n\n" diff --git a/test/suite2.janet b/test/suite2.janet index e82aff27..c08b9baa 100644 --- a/test/suite2.janet +++ b/test/suite2.janet @@ -64,6 +64,12 @@ (assert (= 3 (string/find "abc" " abcdefghijklmnop")) "string/find 1") (assert (= nil (string/find "" "")) "string/find 2") (assert (= 0 (string/find "A" "A")) "string/find 3") +(assert (string/has-prefix? "" "foo") "string/has-prefix? 1") +(assert (string/has-prefix? "fo" "foo") "string/has-prefix? 2") +(assert (not (string/has-prefix? "o" "foo")) "string/has-prefix? 3") +(assert (string/has-suffix? "" "foo") "string/has-suffix? 1") +(assert (string/has-suffix? "oo" "foo") "string/has-suffix? 2") +(assert (not (string/has-suffix? "f" "foo")) "string/has-suffix? 3") (assert (= (string/replace "X" "." "XXX...XXX...XXX") ".XX...XXX...XXX") "string/replace 1") (assert (= (string/replace-all "X" "." "XXX...XXX...XXX") "...............") "string/replace-all 1") (assert (= (string/replace-all "XX" "." "XXX...XXX...XXX") ".X....X....X") "string/replace-all 2")