-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathFormat.fs
62 lines (55 loc) · 1.26 KB
/
Format.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
######################################################
##
## Format:
##
## An implementation of formatted printing routines
## for Mako, building on the "Print.fs" library.
## See below for the list of format sequences.
##
######################################################
: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
;
)