; CLARITAS TIP u32/1 - checked_add_sub_u32.inc
; Public: UADD32CHK, USUB32CHK

; CS617 chapter01-u32calc-v2: checked unsigned 32-bit arithmetic API.
; r006 CANDIDATE (not promoted to accepted lib-set-01).
;
; UADD32CHK: $15..18 lhs, $5..8 rhs => $15..18 sum if in range.
; USUB32CHK: $15..18 lhs, $5..8 rhs => $15..18 difference if in range.
; Both return $4=0 success, $4=1 range error.
; USUB32CHK does not modify $15..18 on underflow.
; UADD32CHK's wrapped intermediate on overflow MUST be discarded by
; the caller; $15..18 is not a valid result on failure.
; Clobbers arithmetic/CPU flags; $4 status. Depends on UADD32/USUB32.
; These wrappers are generic U32 semantics, NOT expression grammar.
#LIST
UADD32CHK:
        CAL     UADD32
; For unsigned addition, wrapped sum < either operand iff overflow.
; $5..8 are unchanged by the accepted UADD32 implementation.
        SBCW    $17,$7
        JR      C,_UACH_OVER
        JR      NZ,_UACH_OK
        SBCW    $15,$5
        JR      C,_UACH_OVER
_UACH_OK:
        LD      $4,0
        RTN
_UACH_OVER:
        LD      $4,1
        RTN

USUB32CHK:
; Test lhs>=rhs, high word first; unsigned subtraction cannot wrap.
        SBCW    $17,$7
        JR      C,_USCH_UNDER
        JR      NZ,_USCH_SAFE
        SBCW    $15,$5
        JR      C,_USCH_UNDER
_USCH_SAFE:
        CAL     USUB32
        LD      $4,0
        RTN
_USCH_UNDER:
        LD      $4,1
        RTN
