\ -*- mode: forth -*-
\ $Id: strcat.gforth,v 1.4 2001/06/24 17:08:56 doug Exp $
\ http://www.bagley.org/~doug/shootout/

\ read NUM from last command line argument
0. argc @ 1- arg >number 2drop drop constant NUM

variable hsiz    32                       hsiz !  \ buffer can hold this much
variable hbuf    hsiz @ allocate throw    hbuf !  \ start of buffer
variable hoff    0                        hoff !  \ current offset in buffer

: STUFF s" hello." ;

: strcat 
    dup                              \ dup strlen on stack
    hsiz @ hoff @ - >                \ if strlen > remaining space
    if                               \ reallocate buffer
    hsiz @ 2* hsiz !             \ double size
    hbuf @ hsiz @ resize throw   \ reallocate buffer
    hbuf !                       \ store (possibly new) buffer start
    then
    swap over                        \ stack: strlen straddr strlen
    hbuf @ hoff @ +
    swap cmove>                      \ append from straddr to hbuf+hoff
    hoff @ + hoff !                  \ update hoff
    ;

: main 
    NUM 0
    do
    STUFF strcat
    loop
    \ as a final result push the resultant string on the stack as if we
    \ were going to use it for something.
    hbuf @ hoff @
    \ and print out the length
    1 u.r cr drop ;

main

bye \ th-th-that's all folks!