-TRAILING is a Forth word which takes an address and character count of a string. It adjusts the character count to exclude trailing spaces.
I used to think -TRAILING should be implemented as a DO LOOP
Code:
: -TRAILING ( ADR CNT1 -- ADR CNT2 )
DUP 0
?DO
2DUP + 1- C@ BL <> ?LEAVE
1-
LOOP ;
However, -TRAILING can be made smaller by implementing it as a BEGIN loop.
Code:
: -TRAILING
BEGIN
DUP
WHILE
1- 2DUP + C@ BL <>
UNTIL
1+
THEN ;
I did not originally set out to write this high level version of -TRAILING . I wanted a faster version of -TRAILING and wrote it as a primitive.
Code:
CODE -TRAILING
BEGIN
0 ,X LDA 1 ,X ORA
NEXT.JMP 0= BRAN
0 ,X LDA
0= IF 1 ,X DEC THEN
0 ,X DEC
CLC
0 ,X LDA 2 ,X ADC N STA
1 ,X LDA 3 ,X ADC N 1+ STA
N )Y LDA BL # CMP
0= NOT UNTIL
' 1+ @ JMP
END-CODE
This is from the source for my Forth's kernel. It is for a metacompiler and NEXT.JMP is a LABEL in the source for the previously defined word.
Code:
LABEL NEXT.JMP
NEXT JMP END-CODE
Although I tested this new version of -TRAILING , it would have been nice to single step through it from within Forth (to see what happens to the values on the data stack).
My Forth has the word TRACE to trace the execution of high level Forth words. TRACE can not trace the execution of a primitive so I wrote a high level version of -TRAILING which works similarly to the primitive version. This version I was able to trace and it is the version I presented as the smaller version of -TRAILING . I will not be using this smaller high level version of -TRAILING . The primitive version is larger but much faster; however, I think the smaller high level version is a good reference implementation for -TRAILING .