;

; Jump Table Helper MACRO
;
; This macro is executed in three forms:
; 1. JT <min>,<max>,<jump table name>,<default label>
; this method is used to branch by way of the jump table, and it must
; appear before method 3
; 2. JT <jump table name>,<index>
; this method is used to mark a node within a jump table, and should
; appear before method 3
; 3. JT <jump table name>,END
; this method builds the jump table in the CONST segment, and should
; appear after all node definitions (uses of method 2)

JT MACRO a:REQ,b:REQ,tName,tDef
LOCAL w,x,y,z
; test if first parameter is a constant number?
; or tName not blank?
IFNB <&tName>
; being able to use this method multiple times for the
; same jump table is a feature ;)
lea edx,[eax-1-b]
IF a NE 0
sub eax,a
ENDIF
xor edx,eax
js @F
jmp &tName[eax*4]
@@:
; initalize global jump table array parameters
tName&_Min EQU a
tName&_Max EQU b
IFDIF <&tDefault>,<>
tName&_Default EQU offset &tDef
ENDIF
ELSE ; add entry to jump table or build table
; test is not second parameter is <END>
IFDIFI <&b>,<END> ; set entry in jump table list
&a&b: ; these could be defined without the macro, too ;)
ELSE ; build jump table and empty global label
CONST SEGMENT
&a: ; jump table label
y = a&_Min
WHILE y LE a&_Max
; test if @CatStr(a,%y) exists and not blank
x TEXTEQU @CatStr(a,%y)
IF OPATTR(x)
dd offset x
ELSE ; error if _Default blank or doesn't exist
;this doesn't work!?
;z TEXTEQU <a&_Default>
;% .ERRNDEF z <JT:Condition not defined in jump table: &x>
;w = OPATTR(a&_Default)
;% .ERRE OPATTR(a&_Default) <JT:Condition not defined in jump table: &x>
dd a&_Default
ENDIF
y = y + 1
ENDM
CONST ENDS
ENDIF
ENDIF
ENDM
Inspired by E?in.
; _One_ MACRO does it all ;)

; Syntax: JT <min>,<max>,<jump table name>,<default label>
; the default label is used for undefined table entries
JT 0,4,tName,tDefault
; execution continues if number out of range...
tDefault:
ret


JT tName,0
mov eax,1
ret

JT tName,1
mov eax,2
ret

JT tName,2
mov eax,3
ret

JT tName,3
mov eax,4
ret

;this line creates the jump table...
JT tName,END
Another cool feature is that you can have many jump tables! Ever try to write an emulator for another processor - this would be very handy.
Posted on 2001-12-08 01:42:46 by bitRAKE