Skip to content

Commit

Permalink
Optimize strnlen, strndup, and strdup
Browse files Browse the repository at this point in the history
  • Loading branch information
calc84maniac authored and mateoconlechuga committed Nov 21, 2024
1 parent e1a3e1d commit d3c7f67
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 68 deletions.
49 changes: 25 additions & 24 deletions src/libc/strdup.src
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,36 @@
section .text
public _strdup
_strdup:
ld hl,-3
call __frameset
ld bc,(ix+6)
push bc
pop de
ex (sp), hl
push de

push hl

push hl
call _strlen
pop bc
pop de

inc hl
push hl

push hl
call _malloc
pop de

pop bc
ld (ix+-3),hl
add hl,de
or a,a
sbc hl,de
jr z,MallocFail
ld bc,(ix+6)
push bc
ld bc,(ix+-3)
push bc
call _strcpy
pop bc
pop bc
MallocFail:
ld hl,(ix+-3)
ld sp,ix
pop ix
pop de

add hl, bc
or a, a
sbc hl, bc
ret z

push hl
ex de, hl
ldir
pop hl
ret

extern __frameset
extern _malloc
extern _strlen
extern _strcpy
extern _malloc
74 changes: 37 additions & 37 deletions src/libc/strndup.src
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,46 @@
section .text
public _strndup
_strndup:
ld hl,-6
call __frameset
ld bc,(ix+6)
push bc
call _strlen
ld (ix+-3),hl
ex de,hl
ld hl,(ix+9)
or a,a
sbc hl,de
jr nc,Greater
ld hl,(ix+9)
ld (ix+-3),hl
Greater:
ld bc,(ix+-3)
inc bc
pop bc
pop de
ex (sp),hl
push de
push bc

push de

push hl
push de
call _strnlen
pop de
pop de

inc hl
push hl

push hl
call _malloc
ld (ix+-6),hl
add hl,bc
or a,a
sbc hl,bc
jr z,MallocFail
ld bc,(ix+-3)
ld hl,(ix+-6)
add hl,bc
ld (hl),0
or a,a
sbc hl,bc
push bc
ld bc,(ix+6)
push bc
pop de

pop bc
pop de

add hl, bc
xor a, a
sbc hl, bc
ret z

ld (hl), a
cpi
dec hl
ret po

push hl
call _memcpy
MallocFail:
ld sp,ix
pop ix
ex de, hl
ldir
ld (de), a
pop hl
ret

extern __frameset
extern _strlen
extern _strnlen
extern _malloc
extern _memcpy
22 changes: 15 additions & 7 deletions src/libc/strnlen.src
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@
section .text
public _strnlen
_strnlen:
pop hl,de,bc
push bc,de,hl
push de
pop hl
xor a,a
inc bc
pop de
pop bc
push bc
push de
push hl
xor a, a
sbc hl, hl
sbc hl, bc
ret z
add hl, bc
sbc hl, de
ex de, hl
cpir
scf
sbc hl,de
add hl, de
ret z
inc hl
ret

0 comments on commit d3c7f67

Please sign in to comment.