-
Notifications
You must be signed in to change notification settings - Fork 2
/
toxml.v
130 lines (111 loc) · 2.3 KB
/
toxml.v
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
module toxml
import strings
struct Toxml {
mut:
sb strings.Builder
stack []string
}
pub fn new() Toxml {
return Toxml {
sb: strings.new_builder(0)
stack: []
}
}
fn escape_key(s string) string {
// TODO : Throw an error if the key is not valid
mut r := s.replace('=', '')
r = r.replace('"', '')
r = r.replace('<', '')
r = r.replace('>', '')
return r
}
fn escape_value(s string) string {
return escape_html(s)
}
fn escape_html(s string) string {
mut r := s.replace('"', '\\"')
r = r.replace('<', '<')
r = r.replace('>', '>')
r = r.replace('\\', '\')
// r = r.replace('\n', '')
r = r.replace('&', '&')
r = r.replace('"', '"')
r = r.replace("'", ''')
return r
}
fn attributes(kvs map[string]string) string {
mut a := ''
for k,v in kvs {
ek := escape_key(k)
ev := escape_value(v)
a += ' $ek="$ev"'
}
return a
}
fn (x &Toxml)indent() string {
return ' '.repeat(x.stack.len)
}
pub fn (mut x Toxml)body(msg string) bool {
if x.stack.len > 0 {
e := escape_html(msg)
x.sb.write_string('$e\n')
return true
}
return false
}
pub fn (mut x Toxml)openclose(tag string, kvs map[string]string) bool {
return x.llopen(tag, kvs, '/', '')
}
pub fn (mut x Toxml)prolog(tag string, kvs map[string]string) bool {
return x.llopen('?' + tag, kvs, '?', '')
}
pub fn (mut x Toxml)comment(tag string) {
x.llopen('!-- ', map[string]string{}, ' --', tag)
}
fn valid(s string) bool {
return s != ''
}
pub fn (mut x Toxml)open(tag string, kvs map[string]string) bool {
if !valid(tag) {
return false
}
r := x.llopen(tag, kvs, '', '')
x.stack << tag
return r
}
fn (mut x Toxml)llopen(tag string, kvs map[string]string, ch string, str string) bool {
if !valid(tag) {
return false
}
attrs := attributes(kvs)
instr := x.indent()
x.sb.write_string('$instr<$tag$str$attrs$ch>\n')
return true
}
fn (mut x Toxml)pop() string {
// return *&string(x.stack.pop())
if x.stack.len == 0 {
return ''
}
tag := x.stack.last()
x.stack.delete(x.stack.len - 1)
return tag
}
pub fn (mut x Toxml)close() bool {
tag := x.pop()
if !valid(tag) {
return false
}
instr := x.indent()
x.sb.write_string('$instr</$tag>\n')
return true
}
pub fn (mut x Toxml)finish() {
for x.stack.len > 0 {
x.close()
}
}
pub fn (mut x Toxml)str() string {
x.finish()
return x.sb.str()
}