Skip to content

Commit 9baa79f

Browse files
nitinseshadrimateoconlechuga
authored andcommitted
Optimize strlcpy
* Use sbc hl, hl rather than ld hl, 0 (carry was already cleared with xor a,a) * Unconditionally do strlen at the start to avoid doing it twice
1 parent caf1ee8 commit 9baa79f

File tree

1 file changed

+17
-24
lines changed

1 file changed

+17
-24
lines changed

src/libc/strlcpy.src

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,6 @@ _strlcpy:
1414

1515
; do min(strlen(src), dsize-1)
1616

17-
ld bc, (iy + 9) ; bc = dsize
18-
19-
; check if dsize is zero
20-
xor a,a ; clear carry and set a to 0
21-
ld hl, 0
22-
sbc hl, bc
23-
jr z, .strlcpy_done ; do nothing if dsize is zero
24-
25-
dec bc ; bc = dsize - 1
26-
27-
push bc ; cpir-based strlen touches bc, so put it on the stack
28-
2917
; strlen(src)
3018
ld hl, (iy + 6) ; hl = pointer to src
3119
xor a,a ; clear carry and set a to 0
@@ -37,7 +25,21 @@ _strlcpy:
3725
sbc hl,bc
3826
; now hl = strlen(src)
3927

40-
pop bc ; get bc back from the stack
28+
push hl ; save this for after dsize check
29+
30+
ld bc, (iy + 9) ; bc = dsize
31+
32+
; check if dsize is zero
33+
xor a,a ; clear carry and set a to 0
34+
sbc hl, hl
35+
sbc hl, bc
36+
jr z, .strlcpy_done ; do nothing if dsize is zero
37+
38+
dec bc ; bc = dsize - 1
39+
40+
; restore hl without changing the stack
41+
pop hl ; get it back
42+
push hl ; save it for the end
4143

4244
; dsize is not zero, compare them
4345
; hl = strlen(src)
@@ -61,7 +63,7 @@ _strlcpy:
6163

6264
; check if bc is zero
6365
xor a,a ; clear carry and set a to 0
64-
ld hl, 0
66+
sbc hl, hl
6567
sbc hl, bc
6668
jr z, .null_terminate ; null terminate if bc is zero
6769

@@ -83,15 +85,6 @@ _strlcpy:
8385
.strlcpy_done:
8486
; return strlen(src)
8587

86-
; strlen(src)
87-
ld hl, (iy + 6) ; hl = pointer to src
88-
xor a,a ; clear carry and set a to 0
89-
ld bc, 0
90-
cpir ; dec bc until byte at (hl) matches a (= NUL)
91-
; calculate HL=-BC-1
92-
sbc hl,hl
93-
scf
94-
sbc hl,bc
95-
; now hl = strlen(src)
88+
pop hl ; get the result of strlen(src) from earlier and put into hl
9689

9790
ret

0 commit comments

Comments
 (0)