Skip to content

Commit

Permalink
Fix return value of strcmp and strncmp, optimize strncmp loop
Browse files Browse the repository at this point in the history
  • Loading branch information
calc84maniac authored and astralaster committed Mar 20, 2024
1 parent 7abe3b5 commit 8ef6850
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 42 deletions.
15 changes: 7 additions & 8 deletions lib/libc/strcmp.src
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
; (c) Copyright 2007-2008 Zilog, Inc.
; int strcmp(register char *s1, register char *s2)
; Changed to remove bug of typecasting difference value to signed char - should be difference of unsigned chars
; Brendan Fletcher 19/03/2024

assume ADL=1

Expand All @@ -14,22 +16,19 @@ _strcmp:
inc hl
ld hl, (hl)

_loop:
.loop:
ld a, (de)
or a, a
jr z, _done
jr z, .done
cpi
inc de
jr z, _loop
jr z, .loop

dec hl
_done:
.done:
sub a, (hl)

ld b, a
rla
sbc hl, hl
ld l, b
ld l, a
ret


63 changes: 29 additions & 34 deletions lib/libc/strncmp.src
Original file line number Diff line number Diff line change
@@ -1,44 +1,39 @@
; (c) Copyright 2007-2008 Zilog, Inc.
; int strncmp(char *s1,char *s2,size_t n)
; Changed to remove bug of typecasting difference value to signed char - should be difference of unsigned chars
; Brendan Fletcher 19/03/2024

ASSUME ADL=1

section .text
public _strncmp
_strncmp:
ld iy, 0
add iy, sp

ld bc, (iy+9)
ld a, (iy+11)
or a, c
or a, b
jr z, _done ; n==0 ? return(0)

ld hl, (iy+6)
ld de, (iy+3)

_cloop:
ld a, (de)
ld iy, 0
add iy, sp

ld bc, (iy+9)
ld a, (iy+11)
or a, c
or a, b
jr z, .done ; n==0 ? return(0)

ld hl, (iy+6)
ld de, (iy+3)

.cloop:
ld a, (de)
or a, a
jr z, .diffnul ; return the difference value if *s1=='\0'
cpi
jr nz, _diff ; return the difference value if mismatch occurs
jp po, _done ; if all the chars over then return(0)
or a, a
jr z, _done ; if *s1=='\0' return(0)
inc de
jr _cloop

_diff:
dec hl
sub a, (hl)
ld b, a
rla
sbc hl, hl
ld l, b
jr nz, .diff ; return the difference value if mismatch occurs
inc de
jp pe, .cloop ; if all the chars not over then loop

.diff:
dec hl
.diffnul:
sub a, (hl)
.done:
sbc hl, hl
ld l, a
ret

_done:
or a, a
sbc hl, hl
ret

0 comments on commit 8ef6850

Please sign in to comment.