babbel 0.1.2

Fast, modular, multi-format serialization and document processing toolkit for Rust
Documentation
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Cross-format conversion matrix for the Babbel ecosystem.
//!
//! Provides effortless conversion pipelines between JSON, YAML, XML, Bencode,
//! CSV, TSV, INI, and JSON Lines.

#[cfg(feature = "json")]
use babbel_json as json_lib;
#[cfg(feature = "yaml")]
use babbel_yaml as yaml_lib;
#[cfg(feature = "bencode")]
use babbel_bencode as bencode_lib;
#[cfg(feature = "xml")]
use babbel_xml as xml_lib;

use babbel_core::{
    csv::emit_csv_to, ini::emit_ini_to, parse_csv, parse_ini, BabbelError, Buffer,
    CsvOptions, FormatEmitter, FormatParser, IniOptions, JsonEmitter, Value, YamlEmitter,
};

/// Supported serialization format identifiers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Format {
    Json,
    Yaml,
    Xml,
    Bencode,
    Csv,
    Tsv,
    Ini,
    JsonLines,
}

/// Configuration options for cross-format conversions.
#[derive(Debug, Clone)]
pub struct ConversionOptions {
    /// Whether to format output with pretty-printing and indentation.
    pub pretty: bool,
    /// Number of spaces for pretty indentation.
    pub indent: usize,
}

impl Default for ConversionOptions {
    fn default() -> Self {
        Self {
            pretty: false,
            indent: 2,
        }
    }
}

impl ConversionOptions {
    /// Create options with pretty-printing enabled.
    pub fn pretty() -> Self {
        Self {
            pretty: true,
            indent: 2,
        }
    }

    /// Set custom indentation spaces.
    pub fn with_indent(mut self, indent: usize) -> Self {
        self.indent = indent;
        self
    }
}

/// Generic, open-ended conversion pipeline from any format parser to any format emitter (OCP & DIP).
pub fn convert_text<P: FormatParser, E: FormatEmitter>(
    input: &str,
    parser: &P,
    emitter: &E,
) -> Result<String, BabbelError> {
    convert_text_with_options(input, parser, emitter, &ConversionOptions::default())
}

/// Generic, open-ended conversion pipeline with custom options (OCP & DIP).
pub fn convert_text_with_options<P: FormatParser, E: FormatEmitter>(
    input: &str,
    parser: &P,
    emitter: &E,
    options: &ConversionOptions,
) -> Result<String, BabbelError> {
    let value = parser.parse_str(input)?;
    let mut dest = Buffer::new();
    if options.pretty {
        emitter.emit_pretty(&value, &mut dest, options.indent)?;
    } else {
        emitter.emit(&value, &mut dest)?;
    }
    Ok(dest.to_string())
}

/// Generic, open-ended conversion pipeline from byte inputs to byte outputs (OCP & DIP).
pub fn convert_bytes<P: FormatParser, E: FormatEmitter>(
    input: &[u8],
    parser: &P,
    emitter: &E,
) -> Result<Vec<u8>, BabbelError> {
    let value = parser.parse_bytes(input)?;
    let mut dest = Buffer::new();
    emitter.emit(&value, &mut dest)?;
    Ok(dest.into_vec())
}

/// JSON parser implementing `FormatParser`.
#[cfg(feature = "json")]
#[derive(Debug, Default, Clone, Copy)]
pub struct JsonParser;

#[cfg(feature = "json")]
impl FormatParser for JsonParser {
    fn parse_str(&self, input: &str) -> Result<Value, BabbelError> {
        let node = json_lib::from_str(input)?;
        Ok(Value::from(&node))
    }
}

/// YAML parser implementing `FormatParser`.
#[cfg(feature = "yaml")]
#[derive(Debug, Default, Clone, Copy)]
pub struct YamlParser;

#[cfg(feature = "yaml")]
impl FormatParser for YamlParser {
    fn parse_str(&self, input: &str) -> Result<Value, BabbelError> {
        let node = yaml_lib::parse_string(input)?;
        Ok(Value::from(&node))
    }
}

/// Bencode parser implementing `FormatParser`.
#[cfg(feature = "bencode")]
#[derive(Debug, Default, Clone, Copy)]
pub struct BencodeParser;

#[cfg(feature = "bencode")]
impl FormatParser for BencodeParser {
    fn parse_str(&self, input: &str) -> Result<Value, BabbelError> {
        self.parse_bytes(input.as_bytes())
    }

    fn parse_bytes(&self, input: &[u8]) -> Result<Value, BabbelError> {
        let node = bencode_lib::parse_bytes(input)?;
        Ok(Value::from(&node))
    }
}

/// XML parser implementing `FormatParser`.
#[cfg(feature = "xml")]
#[derive(Debug, Default, Clone, Copy)]
pub struct XmlParser;

#[cfg(feature = "xml")]
impl FormatParser for XmlParser {
    fn parse_str(&self, input: &str) -> Result<Value, BabbelError> {
        let doc = xml_lib::parse(input)?;
        let name = doc.get_root_element_name().unwrap_or("xml").to_string();
        Ok(Value::Object(vec![(name, Value::String(input.to_string()))]))
    }
}

/// CSV parser implementing `FormatParser`.
#[derive(Debug, Default, Clone)]
pub struct CsvParser {
    pub options: CsvOptions,
}

impl FormatParser for CsvParser {
    fn parse_str(&self, input: &str) -> Result<Value, BabbelError> {
        parse_csv(input, &self.options)
    }
}

/// CSV emitter implementing `FormatEmitter`.
#[derive(Debug, Default, Clone)]
pub struct CsvEmitter {
    pub options: CsvOptions,
}

impl FormatEmitter for CsvEmitter {
    fn emit(&self, value: &Value, destination: &mut dyn babbel_core::IDestination) -> Result<(), BabbelError> {
        emit_csv_to(value, &self.options, destination)
    }
}

/// TSV parser implementing `FormatParser`.
#[derive(Debug, Clone)]
pub struct TsvParser {
    pub options: CsvOptions,
}

impl Default for TsvParser {
    fn default() -> Self {
        Self {
            options: CsvOptions::tsv(),
        }
    }
}

impl FormatParser for TsvParser {
    fn parse_str(&self, input: &str) -> Result<Value, BabbelError> {
        parse_csv(input, &self.options)
    }
}

/// TSV emitter implementing `FormatEmitter`.
#[derive(Debug, Clone)]
pub struct TsvEmitter {
    pub options: CsvOptions,
}

impl Default for TsvEmitter {
    fn default() -> Self {
        Self {
            options: CsvOptions::tsv(),
        }
    }
}

impl FormatEmitter for TsvEmitter {
    fn emit(&self, value: &Value, destination: &mut dyn babbel_core::IDestination) -> Result<(), BabbelError> {
        emit_csv_to(value, &self.options, destination)
    }
}

/// INI parser implementing `FormatParser`.
#[derive(Debug, Default, Clone)]
pub struct IniParser {
    pub options: IniOptions,
}

impl FormatParser for IniParser {
    fn parse_str(&self, input: &str) -> Result<Value, BabbelError> {
        parse_ini(input, &self.options)
    }
}

/// INI emitter implementing `FormatEmitter`.
#[derive(Debug, Default, Clone)]
pub struct IniEmitter {
    pub options: IniOptions,
}

impl FormatEmitter for IniEmitter {
    fn emit(&self, value: &Value, destination: &mut dyn babbel_core::IDestination) -> Result<(), BabbelError> {
        emit_ini_to(value, &self.options, destination)
    }
}

/// JSON Lines parser implementing `FormatParser`.
#[cfg(feature = "json")]
#[derive(Debug, Default, Clone, Copy)]
pub struct JsonLinesParser;

#[cfg(feature = "json")]
impl FormatParser for JsonLinesParser {
    fn parse_str(&self, input: &str) -> Result<Value, BabbelError> {
        let nodes = json_lib::parse_json_lines(input).map_err(BabbelError::syntax)?;
        let values: Vec<Value> = nodes.iter().map(Value::from).collect();
        Ok(Value::Array(values))
    }
}

/// JSON Lines emitter implementing `FormatEmitter`.
#[cfg(feature = "json")]
#[derive(Debug, Default, Clone, Copy)]
pub struct JsonLinesEmitter;

#[cfg(feature = "json")]
impl FormatEmitter for JsonLinesEmitter {
    fn emit(&self, value: &Value, destination: &mut dyn babbel_core::IDestination) -> Result<(), BabbelError> {
        let records = match value {
            Value::Array(arr) => arr.as_slice(),
            single => core::slice::from_ref(single),
        };
        for r in records {
            let mut buf = babbel_core::BufferDestination::new();
            JsonEmitter.emit(r, &mut buf)?;
            destination.add_bytes(&buf.to_string());
            destination.add_byte(b'\n');
        }
        Ok(())
    }
}

// =========================================================================
// Convenience Cross-Format Conversion Functions
// =========================================================================

/// Convert JSON string to YAML string.
#[cfg(all(feature = "json", feature = "yaml"))]
pub fn json_to_yaml(json: &str) -> Result<String, String> {
    let node = json_lib::from_str(json).map_err(|e| e.to_string())?;
    let mut dest = json_lib::BufferDestination::new();
    json_lib::to_yaml(&node, &mut dest)?;
    Ok(dest.to_string())
}

/// Convert JSON string to XML string.
#[cfg(all(feature = "json", feature = "xml"))]
pub fn json_to_xml(json: &str) -> Result<String, String> {
    let node = json_lib::from_str(json).map_err(|e| e.to_string())?;
    let mut dest = json_lib::BufferDestination::new();
    json_lib::to_xml(&node, &mut dest)?;
    Ok(dest.to_string())
}

/// Convert JSON string to Bencode byte vector.
#[cfg(all(feature = "json", feature = "bencode"))]
pub fn json_to_bencode(json: &str) -> Result<Vec<u8>, String> {
    let node = json_lib::from_str(json).map_err(|e| e.to_string())?;
    let mut dest = json_lib::BufferDestination::new();
    json_lib::to_bencode(&node, &mut dest)?;
    Ok(dest.buffer)
}

/// Convert YAML string to JSON string.
#[cfg(all(feature = "yaml", feature = "json"))]
pub fn yaml_to_json(yaml: &str) -> Result<String, String> {
    let node = yaml_lib::parse_string(yaml).map_err(|e| e.to_string())?;
    let mut dest = yaml_lib::BufferDestination::new();
    yaml_lib::to_json(&node, &mut dest).map_err(|e| e.to_string())?;
    Ok(dest.to_string())
}

/// Convert YAML string to XML string.
#[cfg(all(feature = "yaml", feature = "xml"))]
pub fn yaml_to_xml(yaml: &str) -> Result<String, String> {
    let node = yaml_lib::parse_string(yaml).map_err(|e| e.to_string())?;
    let mut dest = yaml_lib::BufferDestination::new();
    yaml_lib::to_xml(&node, &mut dest).map_err(|e| e.to_string())?;
    Ok(dest.to_string())
}

/// Convert Bencode binary payload to JSON string.
#[cfg(all(feature = "bencode", feature = "json"))]
pub fn bencode_to_json(bencode: &[u8]) -> Result<String, String> {
    let node = bencode_lib::parse_bytes(bencode).map_err(|e| e.to_string())?;
    let mut dest = bencode_lib::BufferDestination::new();
    bencode_lib::to_json(&node, &mut dest)?;
    Ok(dest.to_string())
}

/// Convert Bencode binary payload to YAML string.
#[cfg(all(feature = "bencode", feature = "yaml"))]
pub fn bencode_to_yaml(bencode: &[u8]) -> Result<String, String> {
    let node = bencode_lib::parse_bytes(bencode).map_err(|e| e.to_string())?;
    let mut dest = bencode_lib::BufferDestination::new();
    bencode_lib::to_yaml(&node, &mut dest)?;
    Ok(dest.to_string())
}

/// Convert Bencode binary payload to XML string.
#[cfg(all(feature = "bencode", feature = "xml"))]
pub fn bencode_to_xml(bencode: &[u8]) -> Result<String, String> {
    let node = bencode_lib::parse_bytes(bencode).map_err(|e| e.to_string())?;
    let mut dest = bencode_lib::BufferDestination::new();
    bencode_lib::to_xml(&node, &mut dest)?;
    Ok(dest.to_string())
}

// =========================================================================
// Text Format Conversions (CSV, TSV, INI, JSON Lines)
// =========================================================================

/// Convert CSV string to JSON array string.
#[cfg(feature = "json")]
pub fn csv_to_json(csv: &str) -> Result<String, BabbelError> {
    convert_text(csv, &CsvParser::default(), &JsonEmitter)
}

/// Convert JSON string (array of objects or rows) to CSV string.
#[cfg(feature = "json")]
pub fn json_to_csv(json: &str) -> Result<String, BabbelError> {
    convert_text(json, &JsonParser, &CsvEmitter::default())
}

/// Convert TSV string to JSON array string.
#[cfg(feature = "json")]
pub fn tsv_to_json(tsv: &str) -> Result<String, BabbelError> {
    convert_text(tsv, &TsvParser::default(), &JsonEmitter)
}

/// Convert JSON string (array of objects or rows) to TSV string.
#[cfg(feature = "json")]
pub fn json_to_tsv(json: &str) -> Result<String, BabbelError> {
    convert_text(json, &JsonParser, &TsvEmitter::default())
}

/// Convert CSV string to YAML string.
#[cfg(feature = "yaml")]
pub fn csv_to_yaml(csv: &str) -> Result<String, BabbelError> {
    convert_text(csv, &CsvParser::default(), &YamlEmitter)
}

/// Convert YAML string to CSV string.
#[cfg(feature = "yaml")]
pub fn yaml_to_csv(yaml: &str) -> Result<String, BabbelError> {
    convert_text(yaml, &YamlParser, &CsvEmitter::default())
}

/// Convert INI string to JSON object string.
#[cfg(feature = "json")]
pub fn ini_to_json(ini: &str) -> Result<String, BabbelError> {
    convert_text(ini, &IniParser::default(), &JsonEmitter)
}

/// Convert JSON object string to INI configuration string.
#[cfg(feature = "json")]
pub fn json_to_ini(json: &str) -> Result<String, BabbelError> {
    convert_text(json, &JsonParser, &IniEmitter::default())
}

/// Convert INI string to YAML string.
#[cfg(feature = "yaml")]
pub fn ini_to_yaml(ini: &str) -> Result<String, BabbelError> {
    convert_text(ini, &IniParser::default(), &YamlEmitter)
}

/// Convert YAML object string to INI configuration string.
#[cfg(feature = "yaml")]
pub fn yaml_to_ini(yaml: &str) -> Result<String, BabbelError> {
    convert_text(yaml, &YamlParser, &IniEmitter::default())
}

/// Convert JSON Lines string to JSON array string.
#[cfg(feature = "json")]
pub fn jsonlines_to_json(jsonl: &str) -> Result<String, BabbelError> {
    convert_text(jsonl, &JsonLinesParser, &JsonEmitter)
}

/// Convert JSON string to JSON Lines string.
#[cfg(feature = "json")]
pub fn json_to_jsonlines(json: &str) -> Result<String, BabbelError> {
    convert_text(json, &JsonParser, &JsonLinesEmitter)
}

/// Convert JSON Lines string to CSV string.
#[cfg(feature = "json")]
pub fn jsonlines_to_csv(jsonl: &str) -> Result<String, BabbelError> {
    convert_text(jsonl, &JsonLinesParser, &CsvEmitter::default())
}

/// Convert CSV string to JSON Lines string.
#[cfg(feature = "json")]
pub fn csv_to_jsonlines(csv: &str) -> Result<String, BabbelError> {
    convert_text(csv, &CsvParser::default(), &JsonLinesEmitter)
}