serde_yml/libyml/
emitter.rs

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
use crate::libyml::{self, util::Owned};
use ::libyml::api::ScalarEventData;
use ::libyml::document::{
    yaml_document_end_event_initialize,
    yaml_document_start_event_initialize,
};
use ::libyml::YamlEventT;
use ::libyml::YamlScalarStyleT::YamlLiteralScalarStyle;
use ::libyml::{
    yaml_emitter_delete, yaml_emitter_emit, yaml_emitter_flush,
    yaml_emitter_initialize, yaml_emitter_set_output,
    yaml_emitter_set_unicode, yaml_emitter_set_width,
    yaml_mapping_end_event_initialize,
    yaml_mapping_start_event_initialize, yaml_scalar_event_initialize,
    yaml_sequence_end_event_initialize,
    yaml_sequence_start_event_initialize,
    yaml_stream_end_event_initialize,
    yaml_stream_start_event_initialize, YamlAnyMappingStyle,
    YamlAnySequenceStyle, YamlEmitterT, YamlScalarStyleT,
    YamlSingleQuotedScalarStyle, YamlUtf8Encoding,
};
use std::fmt::Debug;
#[allow(clippy::unsafe_removed_from_name)]
use std::{
    ffi::c_void,
    io,
    mem::{self, MaybeUninit},
    ptr::{self, addr_of_mut},
    slice,
};

/// Errors that can occur during YAML emission.
#[derive(Debug)]
pub enum Error {
    /// Errors related to libyml.
    Libyml(libyml::error::Error),
    /// I/O errors.
    Io(io::Error),
}

/// A YAML emitter.
#[derive(Debug)]
pub struct Emitter<'a> {
    pin: Owned<EmitterPinned<'a>>,
}

/// Represents a pinned emitter for YAML serialization.
///
/// The `EmitterPinned` struct contains the necessary state and resources
/// for emitting YAML documents. It is pinned to a specific lifetime `'a`
/// to ensure that the `write` field remains valid throughout the lifetime
/// of the emitter.
///
/// # Fields
///
/// - `sys`: An instance of `YamlEmitterT` representing the underlying
///   emitter system.
/// - `write`: A boxed trait object implementing the `io::Write` trait,
///   used for writing the emitted YAML data. It is pinned to the lifetime
///   `'a` to ensure it remains valid for the duration of the emitter's
///   lifetime.
/// - `write_error`: An optional `io::Error` used to store any errors that
///   occur during the writing process.
///
/// # Lifetime
///
/// The `EmitterPinned` struct is parameterized by a lifetime `'a`, which
/// represents the lifetime of the `write` field. This ensures that the
/// `write` field remains valid for the entire lifetime of the `EmitterPinned`
/// instance.
pub struct EmitterPinned<'a> {
    sys: YamlEmitterT,
    write: Box<dyn io::Write + 'a>,
    write_error: Option<io::Error>,
}

impl Debug for EmitterPinned<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EmitterPinned")
            .field("sys", &self.sys)
            .field("write_error", &self.write_error)
            .finish()
    }
}

/// YAML event types.
#[derive(Debug)]
pub enum Event<'a> {
    /// Start of a YAML stream.
    StreamStart,
    /// End of a YAML stream.
    StreamEnd,
    /// Start of a YAML document.
    DocumentStart,
    /// End of a YAML document.
    DocumentEnd,
    /// Scalar value.
    Scalar(Scalar<'a>),
    /// Start of a sequence.
    SequenceStart(Sequence),
    /// End of a sequence.
    SequenceEnd,
    /// Start of a mapping.
    MappingStart(Mapping),
    /// End of a mapping.
    MappingEnd,
}

/// Represents a scalar value in YAML.
#[derive(Debug)]
pub struct Scalar<'a> {
    /// Optional tag for the scalar.
    pub tag: Option<String>,
    /// Value of the scalar.
    pub value: &'a str,
    /// Style of the scalar.
    pub style: ScalarStyle,
}

/// Styles for YAML scalars.
#[derive(Clone, Copy, Debug)]
pub enum ScalarStyle {
    /// Any scalar style.
    Any,
    /// Double quoted scalar style.
    DoubleQuoted,
    /// Folded scalar style.
    Folded,
    /// Plain scalar style.
    Plain,
    /// Single quoted scalar style.
    SingleQuoted,
    /// Literal scalar style.
    Literal,
}

/// Represents a YAML sequence.
#[derive(Debug)]
pub struct Sequence {
    /// Optional tag for the sequence.
    pub tag: Option<String>,
}

/// Represents a YAML mapping.
#[derive(Debug)]
pub struct Mapping {
    /// Optional tag for the mapping.
    pub tag: Option<String>,
}

impl<'a> Emitter<'a> {
    /// Creates a new YAML emitter.
    pub fn new(write: Box<dyn io::Write + 'a>) -> Emitter<'a> {
        let owned = Owned::<EmitterPinned<'a>>::new_uninit();
        let pin = unsafe {
            let emitter = addr_of_mut!((*owned.ptr).sys);
            if yaml_emitter_initialize(emitter).fail {
                panic!(
                    "malloc error: {}",
                    libyml::Error::emit_error(emitter)
                );
            }
            yaml_emitter_set_unicode(emitter, true);
            yaml_emitter_set_width(emitter, -1);
            addr_of_mut!((*owned.ptr).write).write(write);
            addr_of_mut!((*owned.ptr).write_error).write(None);
            yaml_emitter_set_output(
                emitter,
                write_handler,
                owned.ptr.cast(),
            );
            Owned::assume_init(owned)
        };
        Emitter { pin }
    }

    /// Emits a YAML event.
    pub fn emit(&mut self, event: Event<'_>) -> Result<(), Error> {
        let mut sys_event = MaybeUninit::<YamlEventT>::uninit();
        let sys_event = sys_event.as_mut_ptr();
        unsafe {
            let emitter = addr_of_mut!((*self.pin.ptr).sys);
            let initialize_status = match event {
                Event::StreamStart => {
                    yaml_stream_start_event_initialize(
                        sys_event,
                        YamlUtf8Encoding,
                    )
                }
                Event::StreamEnd => {
                    yaml_stream_end_event_initialize(sys_event)
                }
                Event::DocumentStart => {
                    let version_directive = ptr::null_mut();
                    let tag_directives_start = ptr::null_mut();
                    let tag_directives_end = ptr::null_mut();
                    let implicit = true;
                    yaml_document_start_event_initialize(
                        sys_event,
                        version_directive,
                        tag_directives_start,
                        tag_directives_end,
                        implicit,
                    )
                }
                Event::DocumentEnd => {
                    let implicit = true;
                    yaml_document_end_event_initialize(
                        sys_event, implicit,
                    )
                }
                Event::Scalar(mut scalar) => {
                    let tag_ptr = scalar.tag.as_mut().map_or_else(
                        ptr::null,
                        |tag| {
                            tag.push('\0');
                            tag.as_ptr()
                        },
                    );
                    let value_ptr = scalar.value.as_ptr();
                    let length = scalar.value.len() as i32;
                    let plain_implicit = tag_ptr.is_null();
                    let quoted_implicit = tag_ptr.is_null();
                    let style = match scalar.style {
                        ScalarStyle::Any => {
                            YamlScalarStyleT::YamlAnyScalarStyle
                        }
                        ScalarStyle::DoubleQuoted => {
                            YamlScalarStyleT::YamlDoubleQuotedScalarStyle
                        }
                        ScalarStyle::Folded => {
                            YamlScalarStyleT::YamlFoldedScalarStyle
                        }
                        ScalarStyle::Plain => {
                            YamlScalarStyleT::YamlPlainScalarStyle
                        }
                        ScalarStyle::SingleQuoted => {
                            YamlSingleQuotedScalarStyle
                        }
                        ScalarStyle::Literal => YamlLiteralScalarStyle,
                    };
                    let event_data = ScalarEventData {
                        anchor: ptr::null(),
                        tag: tag_ptr,
                        value: value_ptr,
                        length,
                        plain_implicit,
                        quoted_implicit,
                        style,
                        _marker: core::marker::PhantomData,
                    };
                    yaml_scalar_event_initialize(sys_event, event_data)
                }
                Event::SequenceStart(mut sequence) => {
                    let tag_ptr = sequence.tag.as_mut().map_or_else(
                        ptr::null,
                        |tag| {
                            tag.push('\0');
                            tag.as_ptr()
                        },
                    );
                    let implicit = tag_ptr.is_null();
                    let style = YamlAnySequenceStyle;
                    yaml_sequence_start_event_initialize(
                        sys_event,
                        ptr::null(),
                        tag_ptr,
                        implicit,
                        style,
                    )
                }
                Event::SequenceEnd => {
                    yaml_sequence_end_event_initialize(sys_event)
                }
                Event::MappingStart(mut mapping) => {
                    let tag_ptr = mapping.tag.as_mut().map_or_else(
                        ptr::null,
                        |tag| {
                            tag.push('\0');
                            tag.as_ptr()
                        },
                    );
                    let implicit = tag_ptr.is_null();
                    let style = YamlAnyMappingStyle;
                    yaml_mapping_start_event_initialize(
                        sys_event,
                        ptr::null(),
                        tag_ptr,
                        implicit,
                        style,
                    )
                }
                Event::MappingEnd => {
                    yaml_mapping_end_event_initialize(sys_event)
                }
            };
            if initialize_status.fail {
                return Err(Error::Libyml(libyml::Error::emit_error(
                    emitter,
                )));
            }
            if yaml_emitter_emit(emitter, sys_event).fail {
                return Err(self.error());
            }
        }
        Ok(())
    }

    /// Flushes the YAML emitter.
    pub fn flush(&mut self) -> Result<(), Error> {
        unsafe {
            let emitter = addr_of_mut!((*self.pin.ptr).sys);
            if yaml_emitter_flush(emitter).fail {
                return Err(self.error());
            }
        }
        Ok(())
    }

    /// Retrieves the inner writer from the YAML emitter.
    #[allow(unused_mut)]
    pub fn into_inner(mut self) -> Box<dyn io::Write + 'a> {
        let sink = Box::new(io::sink());
        unsafe { mem::replace(&mut (*self.pin.ptr).write, sink) }
    }

    /// Retrieves the error from the YAML emitter.
    pub fn error(&mut self) -> Error {
        let emitter = unsafe { &mut *self.pin.ptr };
        if let Some(write_error) = emitter.write_error.take() {
            Error::Io(write_error)
        } else {
            Error::Libyml(unsafe {
                libyml::Error::emit_error(&emitter.sys)
            })
        }
    }
}

/// Writes data to a buffer using a provided callback function.
unsafe fn write_handler(
    data: *mut c_void,
    buffer: *mut u8,
    size: u64,
) -> i32 {
    let data = data.cast::<EmitterPinned<'_>>();
    match io::Write::write_all(unsafe { &mut *(*data).write }, unsafe {
        slice::from_raw_parts(buffer, size as usize)
    }) {
        Ok(()) => 1,
        Err(err) => {
            unsafe {
                (*data).write_error = Some(err);
            }
            0
        }
    }
}

impl Drop for EmitterPinned<'_> {
    /// Drops the YAML emitter, deallocating resources.
    fn drop(&mut self) {
        unsafe { yaml_emitter_delete(&mut self.sys) }
    }
}