diff --git a/lib/python/bytes.x b/lib/python/bytes.x index 5894ced..1d53a4b 100644 --- a/lib/python/bytes.x +++ b/lib/python/bytes.x @@ -96,16 +96,32 @@ (if (null? l) (List reverse acc) (self (rest l) (pair (int->char (first l)) acc))))) ; --- the sequence ------------------------------------------------------------ -(def pb-len (fn (_ l) (List length l))) +; A LENGTH IS THE BUNDLE'S OWN COUNT, not `List length`, which is a +; `List fold` and pays a closure call per element on top of the fold's entry. +(def pb-len (fn (_ l) (python-length l))) (def %pb-ref (fn (_ l i) (List ref i l))) +; k IS A COUNT THE CALLER CLAMPED -- a slice's bound, a needle's length, a +; codec's width -- so it rides the doors; see python-rev-onto for the shape. (def %pb-drop - (fn (self k l) (if (if (<= k 0) #t (null? l)) l (self (- k 1) (rest l))))) + (fn (self k l) + (match + ((eq? l ()) l) + ((python-fx< k 1) l) + (#t (self (python-fx- k 1) (rest l)))))) (def %pb-take (fn (self k l acc) - (if (if (<= k 0) #t (null? l)) (List reverse acc) - (self (- k 1) (rest l) (pair (first l) acc))))) + (match + ((eq? l ()) (python-reverse acc)) + ((python-fx< k 1) (python-reverse acc)) + (#t (self (python-fx- k 1) (rest l) (pair (first l) acc)))))) (def %pb-sub (fn (_ l i n) (%pb-take n (%pb-drop i l) ()))) +; THE WINDOW FROM s TO e of a list of length n. One that runs to the end is +; the list's own tail -- a search reads it and keeps nothing, so copying it +; only made garbage the size of the string. +(def %pb-window + (fn (_ l s e n) + (if (python-fx< e n) (%pb-sub l s (python-fx- e s)) (%pb-drop s l)))) ; PUSH EACH BYTE OF `l` ONTO `b`, which reverses l against b. Both callers ; want that: %pb-cat hands it a reversed a, and the accumulating walks hand @@ -140,33 +156,44 @@ ; --- search ------------------------------------------------------------------ (def %pb-at? (fn (self hay ndl) - (if (null? ndl) #t - (if (null? hay) #f - (if (= (first hay) (first ndl)) (self (rest hay) (rest ndl)) #f))))) + (match + ((eq? ndl ()) #t) + ((eq? hay ()) #f) + ((%py-fx= (first hay) (first ndl)) (self (rest hay) (rest ndl))) + (#t #f)))) (def %pb-find-go (fn (self hay ndl i) - (if (%pb-at? hay ndl) i - (if (null? hay) (- 0 1) (self (rest hay) ndl (+ i 1)))))) + (match + ((%pb-at? hay ndl) i) + ((eq? hay ()) (python-fx- 0 1)) + (#t (self (rest hay) ndl (%py-fx+ i 1)))))) (def %pb-find (fn (_ hay ndl) (%pb-find-go hay ndl 0))) +; The empty needle is found at the very end too, so 'abc'.rfind('') is 3. (def %pb-rfind-go (fn (self hay ndl i best) - (if (null? hay) best - (self (rest hay) ndl (+ i 1) (if (%pb-at? hay ndl) i best))))) + (match + ((eq? hay ()) (if (eq? ndl ()) i best)) + ((%pb-at? hay ndl) (self (rest hay) ndl (%py-fx+ i 1) i)) + (#t (self (rest hay) ndl (%py-fx+ i 1) best))))) (def %pb-rfind (fn (_ hay ndl) (%pb-rfind-go hay ndl 0 (- 0 1)))) ; NON-OVERLAPPING, as Python counts: b"aaa".count(b"aa") is 1. An EMPTY ; needle is found between every pair of bytes and at both ends, which is ; len+1 -- Python says so and every other answer here is a special case -; waiting to be found by a test. +; waiting to be found by a test. The needle's length is taken once, not at +; every match. +(def %pb-count-go + (fn (self hay ndl m acc) + (match + ((eq? hay ()) acc) + ((%pb-at? hay ndl) (self (%pb-drop m hay) ndl m (%py-fx+ acc 1))) + (#t (self (rest hay) ndl m acc))))) (def %pb-count - (fn (self hay ndl acc) - (if (null? ndl) (+ (List length hay) 1) - (if (null? hay) acc - (if (%pb-at? hay ndl) - (self (%pb-drop (List length ndl) hay) ndl (+ acc 1)) - (self (rest hay) ndl acc)))))) + (fn (_ hay ndl acc) + (if (null? ndl) (%py-fx+ (pb-len hay) 1) + (%pb-count-go hay ndl (pb-len ndl) acc)))) (def %pb-starts? (fn (_ l p) (%pb-at? l p))) (def %pb-ends? diff --git a/lib/python/runtime-num.x b/lib/python/runtime-num.x index 297188b..a5e8415 100644 --- a/lib/python/runtime-num.x +++ b/lib/python/runtime-num.x @@ -1195,15 +1195,39 @@ (fn (_ l a i) (let ((v (%py-b-opt a i ()))) (if (null? v) (pb-len l) (%py-b-clamp v (pb-len l)))))) +; +; THE WINDOW A SEARCH READS, for find, index, count and their mirrors on str, +; bytes and bytearray: (start . window), from the args after the needle. The +; length is taken once, and a window running to the end is the list's own +; tail rather than a copy (%pb-window). +; No window -- nil -- when the bounds name none: a start past the end, or +; an end before the start. CPython finds nothing there, not even the empty +; needle, so 'abc'.count('', 5) is 0 and 'abc'.find('', 2, 1) is -1; the +; clamped bounds alone read both as the empty window at the end, which has +; the empty needle once. +(def %py-span + (fn (_ l a) + (let ((n (pb-len l)) (raw (python-boolnorm (%py-b-opt a 1 0)))) + (let ((s (%py-b-clamp raw n)) (e (%py-b-clamp (%py-b-opt a 2 n) n))) + (if (if (< e s) #t (> (if (< raw 0) (+ n raw) raw) n)) + () + (pair s (%pb-window l s e n))))))) + ; A SEARCH IS A SEARCH OF THE WINDOW, and the answer is an index into the -; whole -- so the window's start goes back on before it is returned. +; whole -- so the window's start goes back on before it is returned. The +; needle is taken first, so a wrong one is refused whatever the bounds. +(def %py-search-in + (fn (_ l a n rev) + (let ((sp (%py-span l a))) + (if (null? sp) + (python-fx- 0 1) + (let ((r (if rev (%pb-rfind (rest sp) n) (%pb-find (rest sp) n)))) + (if (python-fx< r 0) r (%py-fx+ r (first sp)))))))) +(def %py-count-in + (fn (_ l a n) + (let ((sp (%py-span l a))) (if (null? sp) 0 (%pb-count (rest sp) n 0))))) (def %py-b-search - (fn (_ l a rev) - (let ((s (%py-b-start l a 1))) - (let ((e (%py-b-end l a 2))) - (let ((w (%pb-sub l s (- e s))) (n (%py-b-needle (first a)))) - (let ((r (if rev (%pb-rfind w n) (%pb-find w n)))) - (if (< r 0) r (+ r s)))))))) + (fn (_ l a rev) (%py-search-in l a (%py-b-needle (first a)) rev))) (def %py-b-args (fn (self args) (if (null? args) () (pair (%py-b-arg (first args)) (self (rest args)))))) (def %py-b-opt @@ -1371,9 +1395,7 @@ ((Str8 =? name "index") (fn (_ . a) (%py-b-index (%py-b-search l a #f)))) ((Str8 =? name "rindex") (fn (_ . a) (%py-b-index (%py-b-search l a #t)))) ((Str8 =? name "count") - (fn (_ . a) - (let ((s (%py-b-start l a 1))) - (%pb-count (%pb-sub l s (- (%py-b-end l a 2) s)) (%py-b-needle (first a)) 0)))) + (fn (_ . a) (%py-count-in l a (%py-b-needle (first a))))) ((Str8 =? name "startswith") (fn (_ . a) (%py-b-affix l a %pb-starts?))) ((Str8 =? name "endswith") (fn (_ . a) (%py-b-affix l a %pb-ends?))) ((Str8 =? name "upper") (fn (_ . a) (mk (%pb-upper l)))) diff --git a/lib/python/runtime-str.x b/lib/python/runtime-str.x index 5a95041..7f265d2 100644 --- a/lib/python/runtime-str.x +++ b/lib/python/runtime-str.x @@ -442,18 +442,10 @@ ; answered 5 where CPython answers -1; only a start actually within the string ; can match. A NEGATIVE start counts from the end, so it is normalised first ; and never trips this. A non-empty needle was already right: its window is -; empty there and the search fails on its own. +; empty there and the search fails on its own. The rule is %py-span's now, +; which bytes and count share. (def %py-s-search - (fn (_ l a rev) - (let ((len (pb-len l))) - (let ((raw (python-boolnorm (%py-s-opt a 1 0)))) - (if (> (if (< raw 0) (+ len raw) raw) len) - (- 0 1) - (let ((s (%py-s-start l a 1))) - (let ((e (%py-s-end l a 2))) - (let ((w (%pb-sub l s (- e s))) (n (%py-s-cps (first a) "sub"))) - (let ((r (if rev (%pb-rfind w n) (%pb-find w n)))) - (if (< r 0) r (+ r s))))))))))) + (fn (_ l a rev) (%py-search-in l a (%py-s-cps (first a) "sub") rev))) (def %py-s-index (fn (_ i) (if (< i 0) (Err raise (lit value) "substring not found" ()) i))) @@ -532,9 +524,7 @@ ((Str8 =? name "index") (fn (_ . a) (%py-s-index (%py-s-search l a #f)))) ((Str8 =? name "rindex") (fn (_ . a) (%py-s-index (%py-s-search l a #t)))) ((Str8 =? name "count") - (fn (_ . a) - (let ((s (%py-s-start l a 1))) - (%pb-count (%pb-sub l s (- (%py-s-end l a 2) s)) (%py-s-cps (first a) "count") 0)))) + (fn (_ . a) (%py-count-in l a (%py-s-cps (first a) "count")))) ((Str8 =? name "startswith") (fn (_ . a) (%py-s-affix l a "startswith" %pb-starts?))) ((Str8 =? name "endswith") (fn (_ . a) (%py-s-affix l a "endswith" %pb-ends?))) ((Str8 =? name "partition") diff --git a/lib/python/util.x b/lib/python/util.x index fd5257e..1d0cd48 100644 --- a/lib/python/util.x +++ b/lib/python/util.x @@ -56,7 +56,7 @@ ; mark it sets is never in an image, and the writer's child, which loads ; from source, sweeps like any other source boot. (module python/core) -(import x/core/doors heap-collect int+ int- int< int* int/ str-byte-len) +(import x/core/doors heap-collect int+ int- int< int= int* int/ str-byte-len) (def %py-from-image (pair () ())) (set! %image-recache-hooks (pair (fn (_) (%set-first! %py-from-image #t)) %image-recache-hooks)) @@ -149,9 +149,18 @@ ; both names below -- and it is worth having spelled out, because ; `(%py-append (python-reverse xs) acc)` is `(python-rev-onto xs acc)` without the ; intermediate list. +; +; THE LIST WALKS ARE `match` OVER `eq?`, not `if` over `null?`. Per element, on +; 10,000, counted with (Heap count): a find written `if`/`null?`/`=`/`+` made +; 157 objects, the same `if` over eq? and the doors 74, and a `match` over them +; 24 -- an `if` costs some 17 objects an evaluation where a `match` costs none +; (x-lang lib/x/core/arithmetic.x), and null? is a call where eq? is the prim. +; A builtin's walk runs inside one Python call, which no collect tick reaches, +; so all of that is held until it returns: s.count on 100,000 characters held +; some 3 GB. (def python-rev-onto (fn (self xs acc) - (if (null? xs) acc (self (rest xs) (pair (first xs) acc))))) + (match ((eq? xs ()) acc) (#t (self (rest xs) (pair (first xs) acc)))))) (def python-reverse (fn (_ xs) (python-rev-onto xs ()))) @@ -164,10 +173,14 @@ (def python-fx- int-) (def python-fx< int<) (def %py-fx* int*) +; Equality of two code points or two bytes: each is a word int the carrier +; made -- a str's code points, a bytes' validated values -- never a program's +; int, which may be a bigint. +(def %py-fx= int=) (def %py-count-from (fn (self xs n) - (if (null? xs) n (self (rest xs) (%py-fx+ n 1))))) + (match ((eq? xs ()) n) (#t (self (rest xs) (%py-fx+ n 1)))))) (def python-length (fn (_ xs) (%py-count-from xs 0))) diff --git a/tests/specs/40-string-search.spec.md b/tests/specs/40-string-search.spec.md index 1bfe293..9d4e37e 100644 --- a/tests/specs/40-string-search.spec.md +++ b/tests/specs/40-string-search.spec.md @@ -47,3 +47,33 @@ ValueError False True False False True False False True False False True False True True False ABC abc Hello World hELLO Abc ``` + +### an empty needle where the bounds name no window, and at the very end + +```python +(python-run "s = 'abc'; b = b'abc'; ba = bytearray(b'abc')\nprint(s.count('', 2, 1), s.count('', 5), s.count('', 3), s.count('', -10), s.count('', 1, -5))\nprint(b.count(b'', 2, 1), b.count(b'', 5), ba.count(b'', 4), b.count(b'', 3))\nprint(s.find('', 2, 1), s.rfind('', 2, 1), b.find(b'', 2, 1), b.find(b'', 5), b.rfind(b'', 5), s.find('', 5))\nprint(s.find('', 3), s.rfind('', -1), s.rfind('', 1, 2), s.find('c', -1), b.rfind(b'b', 0, 2))\nprint('ab'.count('ab', 0, 10**30), b'aaaa'.count(b'aa'), 'aaaa'.rfind('aa'), 'xaxa'.index('a', 2))\nprint('abc'.rfind(''), b'abc'.rfind(b''), 'abc'.rindex('', 1, 2), ''.rfind(''), bytearray(b'ab').rfind(b'', 0, 1))\nprint('abcabc'.count('bc', 2), 'abcabc'.count('bc', 1, 5), 'abcabc'.find('c', 3, 5), ba.find(99, 1))\ntry:\n 'abc'.index('', 2, 1)\nexcept ValueError as e:\n print('ValueError', e)\ntry:\n 'abc'.find(5, 10)\nexcept TypeError:\n print('TypeError')\n") +``` +--- +```output +0 0 1 4 0 +0 0 0 1 +-1 -1 -1 -1 -1 -1 +3 3 2 2 1 +1 2 2 3 +3 3 2 0 1 +1 1 -1 2 +ValueError substring not found +TypeError +``` + +### count and find over a long string, which walk it once and copy nothing + +```python +(python-run "s = 'ab' * 10000\nprint(len(s), s.count('ab'), s.count('a', 1), s.count('ab', 0, 19999))\nprint(s.find('x'), s.rfind('ab'), s.find('ba', 1000), 'x' in s, s.index('b', 19998))\nb = b'ab' * 10000\nprint(b.count(b'ab'), b.find(b'x'), b.rfind(b'a'), b.count(b'b', 10000))\n") +``` +--- +```output +20000 10000 9999 9999 +-1 19998 1001 False 19999 +10000 -1 19998 5000 +```