]> git.sur5r.net Git - cc65/blob - libsrc/common/strstr.s
atari5200: fix COLOR defines' names
[cc65] / libsrc / common / strstr.s
1 ;
2 ; Ullrich von Bassewitz, 11.12.1998
3 ;
4 ; char* strstr (const char* haystack, const char* needle);
5 ;
6
7         .export         _strstr
8         .import         popptr1
9         .importzp       ptr1, ptr2, ptr3, ptr4, tmp1
10
11 _strstr:
12         sta     ptr2            ; Save needle
13         stx     ptr2+1
14         sta     ptr4            ; Setup temp copy for later
15
16         jsr     popptr1         ; Get haystack to ptr1
17
18 ; If needle is empty, return haystack
19
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
23
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).
26
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?
31         beq     @L2             ; Jump if so
32         iny                     ; Next char
33         bne     @L1
34         inc     ptr1+1          ; Bump high byte
35         bne     @L1             ; Branch always
36
37 ; We found the start of needle in haystack
38
39 @L2:    tya                     ; Get offset
40         clc
41         adc     ptr1
42         sta     ptr1            ; Make ptr1 point to start
43         bcc     @L3
44         inc     ptr1+1
45
46 ; ptr1 points to the start of needle now. Setup temporary pointers for the
47 ; search. The low byte of ptr4 is already set.
48
49 @L3:    sta     ptr3
50         lda     ptr1+1
51         sta     ptr3+1
52         lda     ptr2+1
53         sta     ptr4+1
54         ldy     #1              ; First char is identical, so start on second
55
56 ; Do the compare
57
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
62         iny                     ; Next char
63         bne     @L4
64         inc     ptr3+1
65         inc     ptr4+1          ; Bump hi byte of pointers
66         bne     @L4             ; Next char (branch always)
67
68 ; The strings did not compare equal, search next start of needle
69
70 @L5:    ldy     #1              ; Start after this char
71         bne     @L1             ; Branch always
72
73 ; We found the start of needle
74
75 @Found: lda     ptr1
76         ldx     ptr1+1
77         rts
78
79 ; We reached end of haystack without finding needle
80
81 @NotFound:
82         lda     #$00            ; return NULL
83         tax
84         rts
85
86
87
88
89
90
91
92
93
94
95