Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Format, a minimalist format string implementation.
- Loading branch information
1 parent
fa7bf33
commit b5eb777
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
###################################################### | ||
## | ||
## Format: | ||
## | ||
## An implementation of formatted printing routines | ||
## for Mako, building on the "Print.fs" library. | ||
## See below for the list of format sequences. | ||
## | ||
###################################################### | ||
|
||
:include <Print.fs> | ||
|
||
:proto printf | ||
: %% 37 emit ; | ||
|
||
: .hex | ||
16 /mod "0123456789ABCDEF" + @ | ||
swap dup if .hex else drop then emit | ||
; | ||
|
||
:data chars | ||
37 %% # %% - '%' character | ||
99 emit # %c - ascii character | ||
100 .num # %d - decimal number | ||
120 .hex # %x - hexadecimal number | ||
115 type # %s - null-terminated string | ||
102 printf # %f - format string (these work recursively) | ||
110 cr # %n - newline | ||
116 tab # %t - tab | ||
|
||
: dispatch ( char -- ) | ||
chars loop | ||
2dup @ = if break then 2 + | ||
again | ||
swap drop 1 + @ exec | ||
; | ||
|
||
: printf ( ... string -- ) | ||
loop | ||
dup @ -if drop break then | ||
dup @ 37 = if | ||
1 + dup >r @ dispatch r> | ||
else | ||
dup @ emit | ||
then | ||
1 + | ||
again | ||
; | ||
|
||
###################################################### | ||
## | ||
## Usage examples: | ||
## | ||
###################################################### | ||
|
||
( | ||
: main | ||
1 2 3 "%d %d %d%n" printf | ||
"foo" "This dude said '%s'- what's with that?%n" printf | ||
1 2 3 "%d%t%d%t%d%n" printf | ||
45 "%n%t[%d]%n" 27 "%d {%f}%n" printf | ||
0xFF00 0x1AFEBABE "%x %x%n" printf | ||
; | ||
) |