checked_add_sub_u32.inc
Original bytes preserved. This is a browser-readable view.
; ======================================================================
; 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