oxirs-core 0.4.0

Core RDF and SPARQL functionality for OxiRS - native Rust implementation with zero dependencies
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Unified RDF Serializer Interface
//!
//! Provides a consistent API for serializing to all supported RDF formats.
//! Extracted and adapted from OxiGraph with OxiRS enhancements.

use super::error::FormatError;
pub use super::error::SerializeResult;
use super::format::RdfFormat;
use crate::model::{Quad, QuadRef, Triple, TripleRef};
use std::collections::HashMap;
use std::io::Write;

/// Result type for quad serialization operations
pub type QuadSerializeResult = SerializeResult<()>;

/// Writer-based quad serializer
pub struct WriterQuadSerializer<W: Write> {
    inner: Box<dyn QuadSerializer<W>>,
}

impl<W: Write> WriterQuadSerializer<W> {
    /// Create a new writer serializer
    pub fn new(serializer: Box<dyn QuadSerializer<W>>) -> Self {
        Self { inner: serializer }
    }

    /// Serialize a quad
    pub fn serialize_quad<'a>(&mut self, quad: impl Into<QuadRef<'a>>) -> QuadSerializeResult {
        self.inner.serialize_quad(quad.into())
    }

    /// Serialize a triple (placed in default graph)
    pub fn serialize_triple<'a>(
        &mut self,
        triple: impl Into<TripleRef<'a>>,
    ) -> QuadSerializeResult {
        let quad = triple.into().in_graph(None);
        self.serialize_quad(quad)
    }

    /// Serialize multiple quads
    pub fn serialize_quads<I>(&mut self, quads: I) -> QuadSerializeResult
    where
        I: IntoIterator,
        I::Item: Into<QuadRef<'static>>,
    {
        for quad in quads {
            self.inner.serialize_quad(quad.into())?;
        }
        Ok(())
    }

    /// Finish serialization and return the writer
    pub fn finish(self) -> SerializeResult<W> {
        self.inner.finish()
    }
}

/// Trait for serializing quads to a writer
pub trait QuadSerializer<W: Write> {
    /// Serialize a quad
    fn serialize_quad(&mut self, quad: QuadRef<'_>) -> QuadSerializeResult;

    /// Finish serialization and return the writer
    fn finish(self: Box<Self>) -> SerializeResult<W>;
}

/// Extension trait for bulk serialization operations
pub trait QuadSerializerExt<W: Write>: QuadSerializer<W> {
    /// Serialize multiple quads
    fn serialize_quads<I>(&mut self, quads: I) -> QuadSerializeResult
    where
        I: IntoIterator,
        I::Item: Into<QuadRef<'static>>,
    {
        for quad in quads {
            self.serialize_quad(quad.into())?;
        }
        Ok(())
    }
}

/// Blanket implementation for all QuadSerializer types
impl<W: Write, T: QuadSerializer<W>> QuadSerializerExt<W> for T {}

/// Unified RDF serializer supporting all formats
pub struct RdfSerializer {
    format: RdfFormat,
    base_iri: Option<String>,
    prefixes: HashMap<String, String>,
    pretty: bool,
}

impl RdfSerializer {
    /// Create a new serializer for the specified format
    pub fn new(format: RdfFormat) -> Self {
        Self {
            format,
            base_iri: None,
            prefixes: HashMap::new(),
            pretty: false,
        }
    }

    /// Set the base IRI for relative IRI generation
    pub fn with_base_iri(mut self, base_iri: impl Into<String>) -> Self {
        self.base_iri = Some(base_iri.into());
        self
    }

    /// Add a namespace prefix
    pub fn with_prefix(mut self, prefix: impl Into<String>, iri: impl Into<String>) -> Self {
        self.prefixes.insert(prefix.into(), iri.into());
        self
    }

    /// Enable pretty formatting (indentation, line breaks)
    pub fn pretty(mut self) -> Self {
        self.pretty = true;
        self
    }

    /// Create a writer-based serializer
    pub fn for_writer<W: Write + 'static>(self, writer: W) -> WriterQuadSerializer<W> {
        match self.format {
            RdfFormat::Turtle => self.create_turtle_serializer(writer),
            RdfFormat::NTriples => self.create_ntriples_serializer(writer),
            RdfFormat::NQuads => self.create_nquads_serializer(writer),
            RdfFormat::TriG => self.create_trig_serializer(writer),
            RdfFormat::RdfXml => self.create_rdfxml_serializer(writer),
            RdfFormat::JsonLd { .. } => self.create_jsonld_serializer(writer),
            RdfFormat::N3 => self.create_n3_serializer(writer),
        }
    }

    /// Get the format being serialized
    pub fn format(&self) -> RdfFormat {
        self.format.clone()
    }

    /// Get the base IRI
    pub fn base_iri(&self) -> Option<&str> {
        self.base_iri.as_deref()
    }

    /// Get the prefixes
    pub fn prefixes(&self) -> &HashMap<String, String> {
        &self.prefixes
    }

    /// Check if pretty formatting is enabled
    pub fn is_pretty(&self) -> bool {
        self.pretty
    }

    // Format-specific serializer implementations

    fn create_turtle_serializer<W: Write + 'static>(self, writer: W) -> WriterQuadSerializer<W> {
        // Use existing Turtle serializer implementation
        let mut turtle_serializer = super::turtle::TurtleSerializer::new();

        // Apply configuration
        if let Some(base) = self.base_iri {
            turtle_serializer = turtle_serializer.with_base_iri(&base);
        }
        for (prefix, iri) in self.prefixes {
            turtle_serializer = turtle_serializer.with_prefix(&prefix, &iri);
        }
        if self.pretty {
            turtle_serializer = turtle_serializer.pretty();
        }

        WriterQuadSerializer::new(Box::new(turtle_serializer.for_writer(writer)))
    }

    fn create_ntriples_serializer<W: Write + 'static>(self, writer: W) -> WriterQuadSerializer<W> {
        // Use existing N-Triples serializer implementation
        let ntriples_serializer = super::ntriples::NTriplesSerializer::new().for_writer(writer);
        WriterQuadSerializer::new(Box::new(ntriples_serializer))
    }

    fn create_nquads_serializer<W: Write + 'static>(self, writer: W) -> WriterQuadSerializer<W> {
        // Use N-Quads serializer implementation
        let nquads_serializer = super::nquads::NQuadsSerializer::new().for_writer(writer);
        WriterQuadSerializer::new(Box::new(nquads_serializer))
    }

    fn create_trig_serializer<W: Write + 'static>(self, writer: W) -> WriterQuadSerializer<W> {
        // Use TriG serializer implementation
        let mut trig_serializer = super::trig::TriGSerializer::new();

        // Apply configuration
        if let Some(base) = self.base_iri {
            trig_serializer = trig_serializer.with_base_iri(&base);
        }
        for (prefix, iri) in self.prefixes {
            trig_serializer = trig_serializer.with_prefix(&prefix, &iri);
        }
        if self.pretty {
            trig_serializer = trig_serializer.pretty();
        }

        WriterQuadSerializer::new(Box::new(trig_serializer.for_writer(writer)))
    }

    fn create_rdfxml_serializer<W: Write + 'static>(self, writer: W) -> WriterQuadSerializer<W> {
        // Use existing RDF/XML serializer implementation
        let mut rdfxml_serializer = super::rdfxml::RdfXmlSerializer::new();

        // Apply configuration
        if self.pretty {
            rdfxml_serializer = rdfxml_serializer.pretty();
        }

        WriterQuadSerializer::new(Box::new(rdfxml_serializer.for_writer(writer)))
    }

    fn create_jsonld_serializer<W: Write + 'static>(self, writer: W) -> WriterQuadSerializer<W> {
        // Use existing JSON-LD serializer implementation
        let mut jsonld_serializer = super::jsonld::JsonLdSerializer::new();

        // Apply configuration
        if self.pretty {
            jsonld_serializer = jsonld_serializer.pretty();
        }

        WriterQuadSerializer::new(Box::new(jsonld_serializer.for_writer(writer)))
    }

    fn create_n3_serializer<W: Write + 'static>(self, writer: W) -> WriterQuadSerializer<W> {
        // Use N3 serializer implementation
        let mut n3_serializer = super::n3::N3Serializer::new();

        // Apply configuration
        if let Some(base) = self.base_iri {
            n3_serializer = n3_serializer.with_base_iri(&base);
        }
        for (prefix, iri) in self.prefixes {
            n3_serializer = n3_serializer.with_prefix(&prefix, &iri);
        }
        if self.pretty {
            n3_serializer = n3_serializer.pretty();
        }

        WriterQuadSerializer::new(Box::new(n3_serializer.for_writer(writer)))
    }
}

impl Default for RdfSerializer {
    fn default() -> Self {
        Self::new(RdfFormat::default())
    }
}

/// Serialization configuration for fine-grained control
#[derive(Debug, Clone)]
pub struct SerializeConfig {
    /// Use compact formatting
    pub compact: bool,
    /// Indentation string for pretty formatting
    pub indent: String,
    /// Line ending style
    pub line_ending: LineEnding,
    /// Maximum line length for wrapping
    pub max_line_length: Option<usize>,
    /// Sort output by subject/predicate
    pub sort_output: bool,
    /// Include comments in output
    pub include_comments: bool,
    /// Validate output during serialization
    pub validate_output: bool,
}

/// Line ending styles
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LineEnding {
    /// Unix-style line endings (\n)
    Unix,
    /// Windows-style line endings (\r\n)
    Windows,
    /// Mac-style line endings (\r)
    Mac,
    /// Platform-default line endings
    Platform,
}

impl Default for SerializeConfig {
    fn default() -> Self {
        Self {
            compact: false,
            indent: "  ".to_string(),
            line_ending: LineEnding::Platform,
            max_line_length: None,
            sort_output: false,
            include_comments: false,
            validate_output: true,
        }
    }
}

impl LineEnding {
    /// Get the line ending string
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Unix => "\n",
            Self::Windows => "\r\n",
            Self::Mac => "\r",
            Self::Platform => {
                #[cfg(windows)]
                return "\r\n";
                #[cfg(not(windows))]
                return "\n";
            }
        }
    }
}

/// A [`Write`] adapter that buffers all output in memory so it can be
/// re-sorted (line-wise) and/or re-terminated with a custom line ending
/// before being flushed to the wrapped writer on [`finalize`](Self::finalize).
pub struct PostProcessingWriter<W: Write> {
    inner: W,
    buffer: Vec<u8>,
    line_ending: LineEnding,
    sort_output: bool,
}

impl<W: Write> PostProcessingWriter<W> {
    fn new(inner: W, line_ending: LineEnding, sort_output: bool) -> Self {
        Self {
            inner,
            buffer: Vec::new(),
            line_ending,
            sort_output,
        }
    }

    /// Flush the buffered output (optionally sorted) to the inner writer,
    /// using this instance's configured line ending, and return the inner
    /// writer.
    fn finalize(mut self) -> std::io::Result<W> {
        let text = String::from_utf8_lossy(&self.buffer);
        // Split into logical lines, dropping a single trailing empty
        // segment produced by a final line terminator.
        let mut lines: Vec<&str> = text.lines().collect();
        if self.sort_output {
            lines.sort_unstable();
        }
        let ending = self.line_ending.as_str();
        for line in &lines {
            self.inner.write_all(line.as_bytes())?;
            self.inner.write_all(ending.as_bytes())?;
        }
        self.inner.flush()?;
        Ok(self.inner)
    }
}

impl<W: Write> Write for PostProcessingWriter<W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.buffer.extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        // Nothing is written to the inner writer until finalize(); this is
        // intentional since output must be fully buffered before it can be
        // sorted or re-terminated.
        Ok(())
    }
}

/// A quad serializer returned by [`ConfigurableSerializer::for_writer`].
///
/// Wraps either a direct [`WriterQuadSerializer`] (when no post-processing
/// is required) or one operating over a [`PostProcessingWriter`] (when
/// `sort_output` and/or a custom `line_ending` was requested).
pub enum ConfiguredQuadSerializer<W: Write> {
    /// No post-processing: writes flow straight through to `W`.
    Direct(WriterQuadSerializer<W>),
    /// Buffered: writes are collected, then sorted/re-terminated and
    /// flushed to `W` on `finish()`.
    Buffered(WriterQuadSerializer<PostProcessingWriter<W>>),
}

impl<W: Write + 'static> ConfiguredQuadSerializer<W> {
    /// Serialize a quad.
    pub fn serialize_quad<'a>(&mut self, quad: impl Into<QuadRef<'a>>) -> QuadSerializeResult {
        match self {
            Self::Direct(s) => s.serialize_quad(quad),
            Self::Buffered(s) => s.serialize_quad(quad),
        }
    }

    /// Serialize a triple (placed in default graph).
    pub fn serialize_triple<'a>(
        &mut self,
        triple: impl Into<TripleRef<'a>>,
    ) -> QuadSerializeResult {
        match self {
            Self::Direct(s) => s.serialize_triple(triple),
            Self::Buffered(s) => s.serialize_triple(triple),
        }
    }

    /// Finish serialization, applying any configured post-processing, and
    /// return the original writer.
    pub fn finish(self) -> SerializeResult<W> {
        match self {
            Self::Direct(s) => s.finish(),
            Self::Buffered(s) => {
                let post_writer = s.finish()?;
                post_writer.finalize()
            }
        }
    }
}

/// Advanced serializer with configuration support
pub struct ConfigurableSerializer {
    serializer: RdfSerializer,
    config: SerializeConfig,
}

impl ConfigurableSerializer {
    /// Create a new configurable serializer
    pub fn new(format: RdfFormat, config: SerializeConfig) -> Self {
        Self {
            serializer: RdfSerializer::new(format),
            config,
        }
    }

    /// Set base IRI
    pub fn with_base_iri(mut self, base_iri: impl Into<String>) -> Self {
        self.serializer = self.serializer.with_base_iri(base_iri);
        self
    }

    /// Add prefix
    pub fn with_prefix(mut self, prefix: impl Into<String>, iri: impl Into<String>) -> Self {
        self.serializer = self.serializer.with_prefix(prefix, iri);
        self
    }

    /// Create a writer with configuration.
    ///
    /// When `sort_output` is enabled or a non-platform `line_ending` is
    /// requested, output is buffered line-by-line so it can be reordered
    /// and re-terminated before being flushed to `writer` on `finish()`.
    /// Line-oriented formats (N-Triples/N-Quads/Turtle/TriG/N3) benefit
    /// from this; structural formats (RDF/XML, JSON-LD) do not have a
    /// meaningful "line" concept, so `sort_output` is a no-op for them
    /// (their statements are not one-per-line) while `line_ending` still
    /// normalizes the terminator of whatever lines they do emit.
    ///
    /// `indent`, `max_line_length`, and `include_comments` remain
    /// reserved: applying them safely requires format-aware rendering
    /// (e.g. re-wrapping Turtle predicate lists) rather than a
    /// post-processing pass, and are tracked as follow-up work.
    pub fn for_writer<W: Write + 'static>(self, writer: W) -> ConfiguredQuadSerializer<W> {
        // Apply configuration settings and create serializer
        let mut serializer = self.serializer;

        // Apply pretty formatting (negation of compact)
        if !self.config.compact {
            serializer = serializer.pretty();
        }

        let needs_post_processing =
            self.config.sort_output || self.config.line_ending != LineEnding::Platform;

        if needs_post_processing {
            let post_writer =
                PostProcessingWriter::new(writer, self.config.line_ending, self.config.sort_output);
            ConfiguredQuadSerializer::Buffered(serializer.for_writer(post_writer))
        } else {
            ConfiguredQuadSerializer::Direct(serializer.for_writer(writer))
        }
    }

    /// Get the configuration
    pub fn config(&self) -> &SerializeConfig {
        &self.config
    }

    /// Get the serializer
    pub fn serializer(&self) -> &RdfSerializer {
        &self.serializer
    }
}

/// Simple serialization functions for common use cases
pub mod simple {
    use super::*;

    /// Serialize triples to a string in the specified format
    pub fn serialize_triples_to_string(
        triples: &[Triple],
        format: RdfFormat,
    ) -> Result<String, FormatError> {
        let buffer = Vec::new();
        let mut serializer = RdfSerializer::new(format).for_writer(buffer);
        for triple in triples {
            serializer.serialize_triple(triple.as_ref())?;
        }
        let buffer = serializer.finish()?;
        String::from_utf8(buffer).map_err(|e| FormatError::invalid_data(e.to_string()))
    }

    /// Serialize quads to a string in the specified format
    pub fn serialize_quads_to_string(
        quads: &[Quad],
        format: RdfFormat,
    ) -> Result<String, FormatError> {
        let buffer = Vec::new();
        let mut serializer = RdfSerializer::new(format).for_writer(buffer);
        for quad in quads {
            serializer.serialize_quad(quad.as_ref())?;
        }
        let buffer = serializer.finish()?;
        String::from_utf8(buffer).map_err(|e| FormatError::invalid_data(e.to_string()))
    }

    /// Serialize triples to Turtle string
    pub fn serialize_turtle(triples: &[Triple]) -> Result<String, FormatError> {
        serialize_triples_to_string(triples, RdfFormat::Turtle)
    }

    /// Serialize triples to N-Triples string
    pub fn serialize_ntriples(triples: &[Triple]) -> Result<String, FormatError> {
        serialize_triples_to_string(triples, RdfFormat::NTriples)
    }

    /// Serialize quads to N-Quads string
    pub fn serialize_nquads(quads: &[Quad]) -> Result<String, FormatError> {
        serialize_quads_to_string(quads, RdfFormat::NQuads)
    }

    /// Serialize quads to TriG string
    pub fn serialize_trig(quads: &[Quad]) -> Result<String, FormatError> {
        serialize_quads_to_string(quads, RdfFormat::TriG)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_serializer_creation() {
        let serializer = RdfSerializer::new(RdfFormat::Turtle);
        assert_eq!(serializer.format(), RdfFormat::Turtle);
        assert!(serializer.base_iri().is_none());
        assert!(serializer.prefixes().is_empty());
        assert!(!serializer.is_pretty());
    }

    #[test]
    fn test_serializer_configuration() {
        let serializer = RdfSerializer::new(RdfFormat::Turtle)
            .with_base_iri("http://example.org/")
            .with_prefix("ex", "http://example.org/ns#")
            .pretty();

        assert_eq!(serializer.base_iri(), Some("http://example.org/"));
        assert_eq!(
            serializer.prefixes().get("ex"),
            Some(&"http://example.org/ns#".to_string())
        );
        assert!(serializer.is_pretty());
    }

    #[test]
    fn test_configurable_serializer() {
        let config = SerializeConfig {
            compact: true,
            sort_output: true,
            ..Default::default()
        };

        let serializer = ConfigurableSerializer::new(RdfFormat::NQuads, config);
        assert!(serializer.config().compact);
        assert!(serializer.config().sort_output);
    }

    #[test]
    fn test_serialize_config_default() {
        let config = SerializeConfig::default();
        assert!(!config.compact);
        assert_eq!(config.indent, "  ");
        assert_eq!(config.line_ending, LineEnding::Platform);
        assert_eq!(config.max_line_length, None);
        assert!(!config.sort_output);
        assert!(!config.include_comments);
        assert!(config.validate_output);
    }

    #[test]
    fn test_line_ending() {
        assert_eq!(LineEnding::Unix.as_str(), "\n");
        assert_eq!(LineEnding::Windows.as_str(), "\r\n");
        assert_eq!(LineEnding::Mac.as_str(), "\r");
        // Platform depends on the compilation target
    }

    #[test]
    fn test_configurable_serializer_sort_output_applied() {
        use crate::model::{NamedNode, Triple};

        let s = |n: &str| NamedNode::new(format!("http://example.org/{n}")).unwrap();
        let triples = vec![
            Triple::new(s("c"), s("p"), s("z")),
            Triple::new(s("a"), s("p"), s("z")),
            Triple::new(s("b"), s("p"), s("z")),
        ];

        let config = SerializeConfig {
            sort_output: true,
            line_ending: LineEnding::Unix,
            ..Default::default()
        };
        let mut serializer =
            ConfigurableSerializer::new(RdfFormat::NTriples, config).for_writer(Vec::new());
        for triple in &triples {
            serializer.serialize_triple(triple.as_ref()).unwrap();
        }
        let buffer = serializer.finish().unwrap();
        let output = String::from_utf8(buffer).unwrap();
        let lines: Vec<&str> = output.lines().collect();

        // Output must be sorted lexicographically, not insertion order.
        let mut expected = lines.clone();
        expected.sort_unstable();
        assert_eq!(lines, expected);
        assert!(lines[0].contains("/a>"));
        assert!(lines[2].contains("/c>"));
        // Custom line ending was honored (Unix => bare \n, no \r).
        assert!(!output.contains('\r'));
    }

    #[test]
    fn test_configurable_serializer_windows_line_ending() {
        use crate::model::{NamedNode, Triple};

        let s = |n: &str| NamedNode::new(format!("http://example.org/{n}")).unwrap();
        let triple = Triple::new(s("s"), s("p"), s("o"));

        let config = SerializeConfig {
            line_ending: LineEnding::Windows,
            ..Default::default()
        };
        let mut serializer =
            ConfigurableSerializer::new(RdfFormat::NTriples, config).for_writer(Vec::new());
        serializer.serialize_triple(triple.as_ref()).unwrap();
        let buffer = serializer.finish().unwrap();
        let output = String::from_utf8(buffer).unwrap();
        assert!(output.ends_with("\r\n"));
    }
}