; STR_APPEND -- Bounded append of source to destination.
; Inputs: $10/$11 src pointer, $12 src cap, $13/$14 dst pointer,
;         $15 dst cap. Both bounded, NUL-terminated byte strings.
; Outputs: $0 STR_* status, $8 total text length (0 on error).
; Source/destination may overlap; STR_COPY gives memmove-like behavior.
; Requires str_abi.inc and str_copy.inc included ONCE by composer.
; All foreseeable failure paths are atomic (no destination mutation).
; Preserves input $10..$15. Clobbers $0,$8,$9,$16..$17,$20..$21,
; $23..$26, IX, flags. UA bank, $SY=1; zero initializers are immediates; no address wrap.
#LIST
STR_APPEND:
        LD      $8,0
        LD      $0,STR_BCAP
        AN      $12,$12
        JP      Z,_STR_APPEND_RET
        AN      $15,$15
        JP      Z,_STR_APPEND_RET
; Scan original destination to NUL, save its length in $26.
        PRE     IX,$13
        LD      $26,0
_SA_DSCAN:
        LD      $16,(IX+$26)
        AN      $16,$16
        JR      Z,_SA_SINIT
        AD      $26,$SY
        LD      $17,$26
        SBC     $17,$15
        JR      C,_SA_DSCAN
        JR      _SA_UNTER
_SA_SINIT:
        PRE     IX,$10
        LD      $27,0
_SA_SSCAN:
        LD      $16,(IX+$27)
        AN      $16,$16
        JR      Z,_STR_APPEND_FIT
        AD      $27,$SY
        LD      $17,$27
        SBC     $17,$12
        JR      C,_SA_SSCAN
_SA_UNTER:
        LD      $0,STR_UNTR
_STR_APPEND_RET:
        RTN
_STR_APPEND_FIT:
        LD      $28,$26
        AD      $28,$27
        JR      C,_SA_SHORT
        LD      $16,$28
        AD      $16,$SY
        JR      C,_SA_SHORT
        LD      $17,$15
        SBC     $17,$16
        JR      C,_SA_SHORT
; Adjust destination pointer by existing text length; remaining
; capacity includes trailing NUL. STR_COPY handles overlap correctly.
        LD      $29,$15
        LD      $22,$26
        LD      $23,0
        ADW     $13,$22
        LD      $15,$29
        SB      $15,$26
        CAL     STR_COPY
        SBW     $13,$22
        LD      $15,$29
        AN      $0,$0
        JR      NZ,_SA_FAIL
        LD      $8,$28
        RTN
_SA_SHORT:
        LD      $0,STR_NOSP
_SA_FAIL:
        LD      $8,0
        RTN
