2 ; Ullrich von Bassewitz, 11.12.1998
4 ; char* strstr (const char* haystack, const char* needle);
9 .importzp ptr1, ptr2, ptr3, ptr4, tmp1
12 sta ptr2 ; Save needle
14 sta ptr4 ; Setup temp copy for later
16 jsr popptr1 ; Get haystack to ptr1
18 ; If needle is empty, return haystack
20 ; ldy #$00 Y=0 guaranteed by popptr1
21 lda (ptr2),y ; Get first byte of needle
22 beq @Found ; Needle is empty --> we're done
24 ; Search for the beginning of the string (this is not an optimal search
25 ; strategy [in fact, it's pretty dumb], but it's simple to implement).
27 sta tmp1 ; Save start of needle
28 @L1: lda (ptr1),y ; Get next char from haystack
29 beq @NotFound ; Jump if end
30 cmp tmp1 ; Start of needle found?
34 inc ptr1+1 ; Bump high byte
35 bne @L1 ; Branch always
37 ; We found the start of needle in haystack
42 sta ptr1 ; Make ptr1 point to start
46 ; ptr1 points to the start of needle now. Setup temporary pointers for the
47 ; search. The low byte of ptr4 is already set.
54 ldy #1 ; First char is identical, so start on second
58 @L4: lda (ptr4),y ; Get char from needle
59 beq @Found ; Jump if end of needle (-> found)
60 cmp (ptr3),y ; Compare with haystack
61 bne @L5 ; Jump if not equal
65 inc ptr4+1 ; Bump hi byte of pointers
66 bne @L4 ; Next char (branch always)
68 ; The strings did not compare equal, search next start of needle
70 @L5: ldy #1 ; Start after this char
71 bne @L1 ; Branch always
73 ; We found the start of needle
79 ; We reached end of haystack without finding needle
82 lda #$00 ; return NULL