; STR_COPY -- bounded copy with memmove-like overlap.
; Dependencies: str_abi.inc included once by composer; no code helpers.
;
; Input: $10/$11 = source pointer, $12 = readable capacity (1..255)
; $13/$14 = destination pointer, $15 = writable capacity (1..255)
; Output: $0 = STR_*; $8 = copied text length (0..254) on success,
; 0 on error. Success writes exactly length + 1 bytes incl NUL.
; Preconditions: same UA-selected bank; $SY=1; zero initializers are immediates; both declared
; spans must fit in that bank without 16-bit address wrap.
; Overlap: supports source=dest and partial overlap in either direction.
; Failure atomicity: zero cap, unterminated source, and insufficient
; destination space leave destination unchanged (two-phase preflight).
; Unchanged: input $10..$15. Clobbered: $0,$8,$9,$16,$17,$20,$21,IX,
; and flags. No private RAM or external code dependencies.
#LIST
STR_COPY:
LD $8,0
LD $0,STR_BCAP
AN $12,$12
JP Z,_STR_COPY_RET
AN $15,$15
JP Z,_STR_COPY_RET
; Phase 1: inspect source without changing destination.
PRE IX,$10
_STR_COPY_SCAN:
LD $16,(IX+$8)
AN $16,$16
JR Z,_STR_COPY_FIT
AD $8,$SY
LD $9,$8
SBC $9,$12
JR C,_STR_COPY_SCAN
LD $0,STR_UNTR
JR _STR_COPY_FAIL
_STR_COPY_FIT:
; Length is <=254. Therefore (length+1) fits in one byte.
LD $9,$8
AD $9,$SY
LD $16,$15
SBC $16,$9
JR C,_STR_COPY_SHORT
; Phase 2: copy NUL as well. Descending if dest > src, to permit
; overlapping spans (equivalent to memmove on length+1 bytes).
LDW $20,$13
SBCW $20,$10
JR C,_SP_FWRD
JR Z,_SP_FWRD
LD $9,$8
_SP_BACK:
PRE IX,$10
LD $16,(IX+$9)
PRE IX,$13
ST $16,(IX+$9)
AN $9,$9
JR Z,_STR_COPY_OK
SB $9,$SY
JR _SP_BACK
_SP_FWRD:
LD $9,0
_SP_LOOP:
PRE IX,$10
LD $16,(IX+$9)
PRE IX,$13
ST $16,(IX+$9)
LD $17,$9
SBC $17,$8
JR Z,_STR_COPY_OK
AD $9,$SY
JR _SP_LOOP
_STR_COPY_SHORT:
LD $0,STR_NOSP
_STR_COPY_FAIL:
LD $8,0
_STR_COPY_RET:
RTN
_STR_COPY_OK:
LD $0,STR_OK
RTN