Skip to content

Commit 7e29c98

Browse files
committed
add substring (with an alias to subs)
1 parent 0b00c69 commit 7e29c98

3 files changed

Lines changed: 29 additions & 0 deletions

File tree

pixie/stdlib.lisp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,8 @@
485485
(assoc m k (assoc-in (get m k) ks v))
486486
(assoc m k v)))))
487487

488+
(def subs pixie.string/substring)
489+
488490
(defmacro assert
489491
([test]
490492
`(if ~test

pixie/vm/libs/string.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,23 @@ def index_of4(a, sep, start, end):
5454
index_of.set_root(MultiArityFn({2: wrap_fn(index_of2), 3: wrap_fn(index_of3), 4: wrap_fn(index_of4)},
5555
required_arity = 2))
5656

57+
def substring2(a, start):
58+
return substring3(a, start, rt._count(a))
59+
60+
def substring3(a, start, end):
61+
affirm(isinstance(a, String), u"First argument must be a string")
62+
affirm(isinstance(start, Integer) and isinstance(end, Integer), u"Second and third argument must be integers")
63+
start = start.int_val()
64+
end = end.int_val()
65+
if start >= 0 and end >= 0:
66+
return rt.wrap(rt.name(a)[start:end])
67+
else:
68+
runtime_error(u"Second and third argument must be non-negative integers")
69+
70+
substring = intern_var(u"pixie.string", u"substring")
71+
substring.set_root(MultiArityFn({2: wrap_fn(substring2), 3: wrap_fn(substring3)},
72+
required_arity = 2))
73+
5774
@as_var("pixie.string", "upper-case")
5875
def upper_case(a):
5976
a = rt.name(a)

tests/test-strings.lisp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,16 @@
3939

4040
(t/assert= (s/index-of s "h" 1 2) -1)))
4141

42+
(t/deftest test-substring
43+
(let [s "heyhohuh"]
44+
(t/assert= (s/substring s 0) s)
45+
(t/assert= (s/substring s 3) (s/substring s 3 (count s)))
46+
(t/assert= (s/substring s 0 0) "")
47+
(t/assert= (s/substring s 0 3) "hey")
48+
(t/assert= (s/substring s 3 5) "ho")
49+
(t/assert= (s/substring s 5 8) "huh")
50+
(t/assert= (s/substring s 3 10000) "hohuh")))
51+
4252
(t/deftest test-upper-case
4353
(t/assert= (s/lower-case "") "")
4454
(t/assert= (s/upper-case "hey") "HEY")

0 commit comments

Comments
 (0)