forked from toon-format/toon-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwriter.rs
More file actions
324 lines (266 loc) · 9.24 KB
/
writer.rs
File metadata and controls
324 lines (266 loc) · 9.24 KB
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use crate::{
types::{Delimiter, EncodeOptions, ToonResult},
utils::{
string::{is_valid_unquoted_key, needs_quoting, quote_string},
QuotingContext,
},
};
/// Writer that builds TOON output string from JSON values.
pub struct Writer {
buffer: String,
pub(crate) options: EncodeOptions,
active_delimiters: Vec<Delimiter>,
}
impl Writer {
/// Create a new writer with the given options.
pub fn new(options: EncodeOptions) -> Self {
Self {
buffer: String::new(),
active_delimiters: vec![options.delimiter],
options,
}
}
/// Finish writing and return the complete TOON string.
pub fn finish(self) -> String {
self.buffer
}
pub fn write_str(&mut self, s: &str) -> ToonResult<()> {
self.buffer.push_str(s);
Ok(())
}
pub fn write_char(&mut self, ch: char) -> ToonResult<()> {
self.buffer.push(ch);
Ok(())
}
pub fn write_newline(&mut self) -> ToonResult<()> {
self.buffer.push('\n');
Ok(())
}
pub fn write_indent(&mut self, depth: usize) -> ToonResult<()> {
let indent_string = self.options.indent.get_string(depth);
if !indent_string.is_empty() {
self.buffer.push_str(&indent_string);
}
Ok(())
}
pub fn write_delimiter(&mut self) -> ToonResult<()> {
self.buffer.push(self.options.delimiter.as_char());
Ok(())
}
pub fn write_key(&mut self, key: &str) -> ToonResult<()> {
if is_valid_unquoted_key(key) {
self.write_str(key)
} else {
self.write_quoted_string(key)
}
}
/// Write an array header with key, length, and optional field list.
pub fn write_array_header(
&mut self,
key: Option<&str>,
length: usize,
fields: Option<&[String]>,
depth: usize,
) -> ToonResult<()> {
if let Some(k) = key {
if depth > 0 {
self.write_indent(depth)?;
}
self.write_key(k)?;
}
self.write_char('[')?;
self.write_str(&length.to_string())?;
// Only write delimiter in header if it's not comma (comma is default/implied)
if self.options.delimiter != Delimiter::Comma {
self.write_delimiter()?;
}
self.write_char(']')?;
// Write field list for tabular arrays: {field1,field2}
if let Some(field_list) = fields {
self.write_char('{')?;
for (i, field) in field_list.iter().enumerate() {
if i > 0 {
self.write_delimiter()?;
}
self.write_key(field)?;
}
self.write_char('}')?;
}
self.write_char(':')
}
/// Write an empty array header.
pub fn write_empty_array_with_key(
&mut self,
key: Option<&str>,
depth: usize,
) -> ToonResult<()> {
if let Some(k) = key {
if depth > 0 {
self.write_indent(depth)?;
}
self.write_key(k)?;
}
self.write_char('[')?;
self.write_str("0")?;
if self.options.delimiter != Delimiter::Comma {
self.write_delimiter()?;
}
self.write_char(']')?;
self.write_char(':')
}
pub fn needs_quoting(&self, s: &str, context: QuotingContext) -> bool {
// Use active delimiter for array values, document delimiter for object values
let delim_char = match context {
QuotingContext::ObjectValue => self.get_document_delimiter_char(),
QuotingContext::ArrayValue => self.get_active_delimiter_char(),
};
needs_quoting(s, delim_char)
}
pub fn write_quoted_string(&mut self, s: &str) -> ToonResult<()> {
self.write_str("e_string(s))
}
pub fn write_value(&mut self, s: &str, context: QuotingContext) -> ToonResult<()> {
if self.needs_quoting(s, context) {
self.write_quoted_string(s)
} else {
self.write_str(s)
}
}
/// Push a new delimiter onto the stack (for nested arrays with different
/// delimiters).
pub fn push_active_delimiter(&mut self, delim: Delimiter) {
self.active_delimiters.push(delim);
}
/// Pop the active delimiter, keeping at least one (the document default).
pub fn pop_active_delimiter(&mut self) {
if self.active_delimiters.len() > 1 {
self.active_delimiters.pop();
}
}
fn get_active_delimiter_char(&self) -> char {
self.active_delimiters
.last()
.unwrap_or(&self.options.delimiter)
.as_char()
}
fn get_document_delimiter_char(&self) -> char {
self.options.delimiter.as_char()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_writer_basic() {
let opts = EncodeOptions::default();
let mut writer = Writer::new(opts);
writer.write_str("hello").unwrap();
writer.write_str(" ").unwrap();
writer.write_str("world").unwrap();
assert_eq!(writer.finish(), "hello world");
}
#[test]
fn test_write_delimiter() {
let mut opts = EncodeOptions::default();
let mut writer = Writer::new(opts.clone());
writer.write_str("a").unwrap();
writer.write_delimiter().unwrap();
writer.write_str("b").unwrap();
assert_eq!(writer.finish(), "a,b");
opts = opts.with_delimiter(Delimiter::Pipe);
let mut writer = Writer::new(opts);
writer.write_str("a").unwrap();
writer.write_delimiter().unwrap();
writer.write_str("b").unwrap();
assert_eq!(writer.finish(), "a|b");
}
#[test]
fn test_write_indent() {
let opts = EncodeOptions::default();
let mut writer = Writer::new(opts);
writer.write_indent(0).unwrap();
writer.write_str("a").unwrap();
writer.write_newline().unwrap();
writer.write_indent(1).unwrap();
writer.write_str("b").unwrap();
writer.write_newline().unwrap();
writer.write_indent(2).unwrap();
writer.write_str("c").unwrap();
assert_eq!(writer.finish(), "a\n b\n c");
}
#[test]
fn test_write_array_header() {
let opts = EncodeOptions::default();
let mut writer = Writer::new(opts);
writer
.write_array_header(Some("items"), 3, None, 0)
.unwrap();
assert_eq!(writer.finish(), "items[3]:");
let opts = EncodeOptions::default();
let mut writer = Writer::new(opts);
let fields = vec!["id".to_string(), "name".to_string()];
writer
.write_array_header(Some("users"), 2, Some(&fields), 0)
.unwrap();
assert_eq!(writer.finish(), "users[2]{id,name}:");
}
#[test]
fn test_write_array_header_with_pipe_delimiter() {
let opts = EncodeOptions::new().with_delimiter(Delimiter::Pipe);
let mut writer = Writer::new(opts);
writer
.write_array_header(Some("items"), 3, None, 0)
.unwrap();
assert_eq!(writer.finish(), "items[3|]:");
let opts = EncodeOptions::new().with_delimiter(Delimiter::Pipe);
let mut writer = Writer::new(opts);
let fields = vec!["id".to_string(), "name".to_string()];
writer
.write_array_header(Some("users"), 2, Some(&fields), 0)
.unwrap();
assert_eq!(writer.finish(), "users[2|]{id|name}:");
}
#[test]
fn test_write_key_with_special_chars() {
let opts = EncodeOptions::default();
let mut writer = Writer::new(opts);
writer.write_key("normal_key").unwrap();
assert_eq!(writer.finish(), "normal_key");
let opts = EncodeOptions::default();
let mut writer = Writer::new(opts);
writer.write_key("key:with:colons").unwrap();
assert_eq!(writer.finish(), "\"key:with:colons\"");
}
#[test]
fn test_write_quoted_string() {
let opts = EncodeOptions::default();
let mut writer = Writer::new(opts);
writer.write_quoted_string("hello world").unwrap();
assert_eq!(writer.finish(), "\"hello world\"");
let opts = EncodeOptions::default();
let mut writer = Writer::new(opts);
writer.write_quoted_string("say \"hi\"").unwrap();
assert_eq!(writer.finish(), r#""say \"hi\"""#);
}
#[test]
fn test_needs_quoting() {
let opts = EncodeOptions::default();
let writer = Writer::new(opts);
let ctx = QuotingContext::ObjectValue;
assert!(!writer.needs_quoting("hello", ctx));
assert!(writer.needs_quoting("hello,world", ctx));
assert!(writer.needs_quoting("true", ctx));
assert!(writer.needs_quoting("false", ctx));
assert!(writer.needs_quoting("null", ctx));
assert!(writer.needs_quoting("123", ctx));
assert!(writer.needs_quoting("", ctx));
assert!(writer.needs_quoting("hello:world", ctx));
}
#[test]
fn test_write_empty_array() {
let opts = EncodeOptions::default();
let mut writer = Writer::new(opts);
writer.write_empty_array_with_key(Some("items"), 0).unwrap();
assert_eq!(writer.finish(), "items[0]:");
}
}