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
use std::io::Write;
use std::convert::{TryInto, TryFrom};

use crate::errors::tool::ToolError;
use crate::spec_util::validate_tag_path;

use super::tag_iterator_util::EBMLSize::{self, Known, Unknown};

use super::tools::{Vint, is_vint};
use super::specs::{EbmlSpecification, EbmlTag, TagDataType, Master};

use super::errors::tag_writer::TagWriterError;

///
/// Options that can be passed to the writer to customize written output
/// 
pub struct WriteOptions
{
    size_byte_length: Option<usize>,
    unknown_sized_element: bool,
}

impl WriteOptions {
    ///
    /// Specifies the byte length for the element's "size"
    /// 
    /// This function generates [`WriteOptions`] that will force the Element Data Size to be a specific number of bytes for the written tag.
    /// 
    /// ## Panics
    /// 
    /// This method asserts that `len` is within 1-8 (inclusive).  Values outside this range will cause a panic.
    /// 
    pub fn set_size_byte_count(len: usize) -> Self {
        assert!(len > 0 && len < 9, "Size byte count for written vints must be within 1-8 (inclusive)");
        Self {
            size_byte_length: Some(len),
            unknown_sized_element: false
        }
    }

    ///
    /// Specifies that the element has an Unknown Data Size.
    /// 
    /// The [`WriteOptions`] generated by this function allow you to start a tag that doesn't have a known size.  Useful for streaming, or when the data is expected to be too large to fit into memory.  This should *only* be used with Master type tags.
    /// 
    pub fn is_unknown_sized_element() -> Self {
        Self {
            size_byte_length: None,
            unknown_sized_element: true
        }
    }
}

///
/// Provides a tool to write EBML files based on Tags.  Writes to a destination that implements [`std::io::Write`].
///
/// Unlike the [`TagIterator`][`super::TagIterator`], this does not require a specification to write data. This writer provides the [`write_raw()`](#method.write_raw) method which can be used to write data that is outside of any specification.  The regular [`write()`](#method.write) method can be used to write any `TSpec` objects regardless of whether they came from a [`TagIterator`][`super::TagIterator`] or not.
///

pub struct TagWriter<W: Write>
{
    dest: W,
    open_tags: Vec<(u64, EBMLSize, usize)>,
    working_buffer: Vec<u8>,
}

impl<W: Write> TagWriter<W>
{
    /// 
    /// Returns a new [`TagWriter`] instance.
    ///
    /// The `dest` parameter can be anything that implements [`std::io::Write`].
    ///
    pub fn new(dest: W) -> Self {
        TagWriter {
            dest,
            open_tags: Vec::new(),
            working_buffer: Vec::new(),
        }
    }

    ///
    /// Consumes self and returns the underlying write stream.
    /// 
    /// Any incomplete tags are written out before returning the stream.
    /// 
    pub fn into_inner(mut self) -> Result<W, TagWriterError> {
        self.flush()?;
        Ok(self.dest)
    }

    ///
    /// Gets a mutable reference to the underlying write stream.
    /// 
    pub fn get_mut(&mut self) -> &mut W {
        &mut self.dest
    }

    ///
    /// Gets a reference to the underlying write stream.
    /// 
    pub fn get_ref(&self) -> &W {
        &self.dest
    }

    fn start_tag(&mut self, id: u64, size_length: usize) {
        self.open_tags.push((id, Known(self.working_buffer.len()), size_length));
    }

    fn start_unknown_size_tag(&mut self, id: u64) {
        self.working_buffer.extend(id.to_be_bytes().iter().skip_while(|&v| *v == 0u8));
        self.working_buffer.extend_from_slice(&(u64::MAX >> 7).to_be_bytes());
        self.open_tags.push((id, Unknown, 0));
    }

    fn end_tag(&mut self, id: u64) -> Result<(), TagWriterError> {
        match self.open_tags.pop() {
            Some(open_tag) => {
                if open_tag.0 == id {
                    if let Known(start) = open_tag.1 {
                        let size: u64 = self.working_buffer.len()
                            .checked_sub(start).expect("overflow subtracting tag size from working buffer length")
                            .try_into().expect("couldn't convert usize to u64");
    
                        match open_tag.2 {
                            1 => { let size_vint = size.as_vint_with_length::<1>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?; self.working_buffer.splice(start..start, open_tag.0.to_be_bytes().iter().skip_while(|&v| *v == 0u8).chain(size_vint.iter()).copied()); }
                            2 => { let size_vint = size.as_vint_with_length::<2>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?; self.working_buffer.splice(start..start, open_tag.0.to_be_bytes().iter().skip_while(|&v| *v == 0u8).chain(size_vint.iter()).copied()); }
                            3 => { let size_vint = size.as_vint_with_length::<3>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?; self.working_buffer.splice(start..start, open_tag.0.to_be_bytes().iter().skip_while(|&v| *v == 0u8).chain(size_vint.iter()).copied()); }
                            4 => { let size_vint = size.as_vint_with_length::<4>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?; self.working_buffer.splice(start..start, open_tag.0.to_be_bytes().iter().skip_while(|&v| *v == 0u8).chain(size_vint.iter()).copied()); }
                            5 => { let size_vint = size.as_vint_with_length::<5>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?; self.working_buffer.splice(start..start, open_tag.0.to_be_bytes().iter().skip_while(|&v| *v == 0u8).chain(size_vint.iter()).copied()); }
                            6 => { let size_vint = size.as_vint_with_length::<6>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?; self.working_buffer.splice(start..start, open_tag.0.to_be_bytes().iter().skip_while(|&v| *v == 0u8).chain(size_vint.iter()).copied()); }
                            7 => { let size_vint = size.as_vint_with_length::<7>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?; self.working_buffer.splice(start..start, open_tag.0.to_be_bytes().iter().skip_while(|&v| *v == 0u8).chain(size_vint.iter()).copied()); }
                            8 => { let size_vint = size.as_vint_with_length::<8>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?; self.working_buffer.splice(start..start, open_tag.0.to_be_bytes().iter().skip_while(|&v| *v == 0u8).chain(size_vint.iter()).copied()); }
                            _ => { let size_vint = size.as_vint().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?; self.working_buffer.splice(start..start, open_tag.0.to_be_bytes().iter().skip_while(|&v| *v == 0u8).chain(size_vint.iter()).copied()); }
                        };
                    }
                    Ok(())
                } else {
                    Err(TagWriterError::UnexpectedClosingTag { tag_id: id, expected_id: Some(open_tag.0) })
                }
            },
            None => Err(TagWriterError::UnexpectedClosingTag { tag_id: id, expected_id: None })
        }
    }

    fn private_flush(&mut self) -> Result<(), TagWriterError> {
        self.dest.write_all(self.working_buffer.drain(..).as_slice()).map_err(|source| TagWriterError::WriteError { source })?;
        self.dest.flush().map_err(|source| TagWriterError::WriteError { source })
    }

    fn write_unsigned_int_tag<const SIZE_LENGTH: usize>(&mut self, id: u64, data: &u64) -> Result<(), TagWriterError> {
        self.working_buffer.extend(id.to_be_bytes().iter().skip_while(|&v| *v == 0u8));
        let data = *data;

        u8::try_from(data).map(|n| {
            if SIZE_LENGTH == 0 { 
                self.working_buffer.push(0x81); // vint representation of "1"
                self.working_buffer.extend_from_slice(&n.to_be_bytes());
            } else { 
                self.working_buffer.extend_from_slice(&1u8.as_vint_with_length::<SIZE_LENGTH>()?);
                self.working_buffer.extend_from_slice(&n.to_be_bytes());
            }
            Ok(())
        })
        .or_else(|_| u16::try_from(data).map(|n| { 
            if SIZE_LENGTH == 0 { 
                self.working_buffer.push(0x82); // vint representation of "2"
                self.working_buffer.extend_from_slice(&n.to_be_bytes());
            } else { 
                self.working_buffer.extend_from_slice(&2u8.as_vint_with_length::<SIZE_LENGTH>()?);
                self.working_buffer.extend_from_slice(&n.to_be_bytes());
            }
            Ok(())
        }))
        .or_else(|_| u32::try_from(data).map(|n| { 
            if SIZE_LENGTH == 0 { 
                self.working_buffer.push(0x84); // vint representation of "4"
                self.working_buffer.extend_from_slice(&n.to_be_bytes());
            } else { 
                self.working_buffer.extend_from_slice(&4u8.as_vint_with_length::<SIZE_LENGTH>()?);
                self.working_buffer.extend_from_slice(&n.to_be_bytes());
            }
            Ok(())
        }))
        .unwrap_or_else(|_| { 
            if SIZE_LENGTH == 0 { 
                self.working_buffer.push(0x88); // vint representation of "8"
                self.working_buffer.extend_from_slice(&data.to_be_bytes());
            } else { 
                self.working_buffer.extend_from_slice(&8u8.as_vint_with_length::<SIZE_LENGTH>()?);
                self.working_buffer.extend_from_slice(&data.to_be_bytes());
            }
            Ok(())
        }).map_err(|err: ToolError| TagWriterError::TagSizeError(err.to_string()))
    }

    fn write_signed_int_tag<const SIZE_LENGTH: usize>(&mut self, id: u64, data: &i64) -> Result<(), TagWriterError> {
        self.working_buffer.extend(id.to_be_bytes().iter().skip_while(|&v| *v == 0u8));
        let data = *data;
        i8::try_from(data).map(|n| { 
                if SIZE_LENGTH == 0 { 
                    self.working_buffer.push(0x81); // vint representation of "1"
                    self.working_buffer.extend_from_slice(&n.to_be_bytes());
                } else { 
                    self.working_buffer.extend_from_slice(&1u8.as_vint_with_length::<SIZE_LENGTH>()?);
                    self.working_buffer.extend_from_slice(&n.to_be_bytes());
                }
                Ok(())
            })
            .or_else(|_| i16::try_from(data).map(|n| { 
                if SIZE_LENGTH == 0 { 
                    self.working_buffer.push(0x82); // vint representation of "2"
                    self.working_buffer.extend_from_slice(&n.to_be_bytes());
                } else { 
                    self.working_buffer.extend_from_slice(&2u8.as_vint_with_length::<SIZE_LENGTH>()?);
                    self.working_buffer.extend_from_slice(&n.to_be_bytes());
                }
                Ok(())
            }))
            .or_else(|_| i32::try_from(data).map(|n| { 
                if SIZE_LENGTH == 0 { 
                    self.working_buffer.push(0x84); // vint representation of "4"
                    self.working_buffer.extend_from_slice(&n.to_be_bytes());
                } else { 
                    self.working_buffer.extend_from_slice(&4u8.as_vint_with_length::<SIZE_LENGTH>()?);
                    self.working_buffer.extend_from_slice(&n.to_be_bytes());
                }
                Ok(())
            }))
            .unwrap_or_else(|_| { 
                if SIZE_LENGTH == 0 { 
                    self.working_buffer.push(0x88); // vint representation of "8"
                    self.working_buffer.extend_from_slice(&data.to_be_bytes());
                } else { 
                    self.working_buffer.extend_from_slice(&8u8.as_vint_with_length::<SIZE_LENGTH>()?);
                    self.working_buffer.extend_from_slice(&data.to_be_bytes());
                }
                Ok(())
            }).map_err(|err: ToolError| TagWriterError::TagSizeError(err.to_string()))
    }

    fn write_utf8_tag<const SIZE_LENGTH: usize>(&mut self, id: u64, data: &str) -> Result<(), TagWriterError> {
        self.working_buffer.extend(id.to_be_bytes().iter().skip_while(|&v| *v == 0u8));

        let slice: &[u8] = data.as_bytes();
        let size: u64 = slice.len().try_into().expect("couldn't convert usize to u64");
        if SIZE_LENGTH == 0 { 
            let size_vint = size.as_vint().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?;
            self.working_buffer.extend_from_slice(&size_vint);
        } else { 
            let size_vint = size.as_vint_with_length::<SIZE_LENGTH>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?;
            self.working_buffer.extend_from_slice(&size_vint);
        };

        self.working_buffer.extend_from_slice(slice);
        Ok(())
    }

    fn write_binary_tag<const SIZE_LENGTH: usize>(&mut self, id: u64, data: &[u8]) -> Result<(), TagWriterError> {
        self.working_buffer.extend(id.to_be_bytes().iter().skip_while(|&v| *v == 0u8));

        let size: u64 = data.len().try_into().expect("couldn't convert usize to u64");
        if SIZE_LENGTH == 0 {
            let size_vint = size.as_vint().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?;
            self.working_buffer.extend_from_slice(&size_vint);
        } else {
            let size_vint = size.as_vint_with_length::<SIZE_LENGTH>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?;
            self.working_buffer.extend_from_slice(&size_vint);
        }

        self.working_buffer.extend_from_slice(data);
        Ok(())
    }

    fn write_float_tag<const SIZE_LENGTH: usize>(&mut self, id: u64, data: &f64) -> Result<(), TagWriterError> {
        self.working_buffer.extend(id.to_be_bytes().iter().skip_while(|&v| *v == 0u8));
        if SIZE_LENGTH == 0 {
            self.working_buffer.push(0x88); // vint representation of "8"
        } else {
            let size_vint = 8u8.as_vint_with_length::<SIZE_LENGTH>().map_err(|e| TagWriterError::TagSizeError(e.to_string()))?;
            self.working_buffer.extend_from_slice(&size_vint);
        }
        self.working_buffer.extend_from_slice(&data.to_be_bytes());
        Ok(())
    }

    ///
    /// Write a tag to this instance's destination.
    ///
    /// This method writes a tag from any specification.  There are no restrictions on the type of specification being written - it simply needs to implement the [`EbmlSpecification`] and [`EbmlTag`] traits.
    ///
    /// ## Errors
    /// 
    /// This method can error if there is a problem writing the input tag.  The different possible error states are enumerated in [`TagWriterError`].
    ///
    /// ## Panics
    ///
    /// This method can panic if `<TSpec>` is an internally inconsistent specification (i.e. it claims that a specific tag variant is a specific data type but it is not).  This won't happen if the specification being used was created using the [`#[ebml_specification]`](https://docs.rs/ebml-iterable-specification-derive/latest/ebml_iterable_specification_derive/attr.ebml_specification.html) attribute macro.
    ///
    /// ## Examples
    ///
    /// ```no_run
    /// use std::fs::File;
    /// use ebml_iterable::TagWriter;
    /// use ebml_iterable::specs::Master;
    /// # use ebml_iterable_specification::empty_spec::EmptySpec;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut file = File::create("my_ebml_file.ebml")?;
    /// let mut my_writer = TagWriter::new(&mut file);
    /// my_writer.write(&EmptySpec::with_children(
    ///   0x1a45dfa3, 
    ///   vec![EmptySpec::with_data(0x18538067, &[0x01])])
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    pub fn write<TSpec: EbmlSpecification<TSpec> + EbmlTag<TSpec> + Clone>(&mut self, tag: &TSpec) -> Result<(), TagWriterError> {
        self.write_advanced(tag, WriteOptions { size_byte_length: None, unknown_sized_element: false })
    }

    ///
    /// Write a tag to this instance's destination using advanced options.
    /// 
    /// This method is just like the normal [`write()`](#method.write) method, but allows for tailoring the output binary to better suit your needs.  See [`WriteOptions`] for more detail on available options.
    /// 
    /// ## Errors
    /// 
    /// This method can error if there is a problem writing the input tag.  The different possible error states are enumerated in [`TagWriterError`].
    ///
    /// ## Panics
    ///
    /// This method can panic if `<TSpec>` is an internally inconsistent specification (i.e. it claims that a specific tag variant is a specific data type but it is not).  This won't happen if the specification being used was created using the [`#[ebml_specification]`](https://docs.rs/ebml-iterable-specification-derive/latest/ebml_iterable_specification_derive/attr.ebml_specification.html) attribute macro.
    /// 
    pub fn write_advanced<TSpec: EbmlSpecification<TSpec> + EbmlTag<TSpec> + Clone>(&mut self, tag: &TSpec, options: WriteOptions) -> Result<(), TagWriterError> {
        let tag_id = tag.get_id();
        let tag_type = TSpec::get_tag_data_type(tag_id);

        if options.unknown_sized_element {
            match tag_type {
                Some(TagDataType::Master) => {},
                _ => {
                    return Err(TagWriterError::TagSizeError(format!("Cannot write an unknown size for tag of type {tag_type:?}")))
                }
            };
            self.start_unknown_size_tag(tag_id);
        } else {
            let should_validate = tag_type.is_some() && (!matches!(tag_type, Some(TagDataType::Master)) || !matches!(tag.as_master().unwrap_or_else(|| panic!("Bad specification implementation: Tag id {} type was master, but could not get tag!", tag_id)), Master::End));
            if should_validate && !validate_tag_path::<TSpec>(tag_id, self.open_tags.iter().copied()) {
                return Err(TagWriterError::UnexpectedTag { tag_id, current_path: self.open_tags.iter().map(|t| t.0).collect() });
            }

            match options.size_byte_length {
                Some(1) => self.write_explicit_sized::<TSpec, 1>(tag, tag_id, tag_type)?,
                Some(2) => self.write_explicit_sized::<TSpec, 2>(tag, tag_id, tag_type)?,
                Some(3) => self.write_explicit_sized::<TSpec, 3>(tag, tag_id, tag_type)?,
                Some(4) => self.write_explicit_sized::<TSpec, 4>(tag, tag_id, tag_type)?,
                Some(5) => self.write_explicit_sized::<TSpec, 5>(tag, tag_id, tag_type)?,
                Some(6) => self.write_explicit_sized::<TSpec, 6>(tag, tag_id, tag_type)?,
                Some(7) => self.write_explicit_sized::<TSpec, 7>(tag, tag_id, tag_type)?,
                Some(8) => self.write_explicit_sized::<TSpec, 8>(tag, tag_id, tag_type)?,
                _ => self.write_explicit_sized::<TSpec, 0>(tag, tag_id, tag_type)?,
            }
        }

        Ok(())
    }

    fn write_explicit_sized<TSpec: EbmlSpecification<TSpec> + EbmlTag<TSpec> + Clone, const SIZE_LENGTH: usize>(&mut self, tag: &TSpec, tag_id: u64, tag_type: Option<TagDataType>) -> Result<(), TagWriterError> {
        assert!(SIZE_LENGTH < 9, "Vint length must be less than 9 bytes");
        match tag_type {
            Some(TagDataType::UnsignedInt) => {
                let val = tag.as_unsigned_int().unwrap_or_else(|| panic!("Bad specification implementation: Tag id {} type was unsigned int, but could not get tag!", tag_id));
                self.write_unsigned_int_tag::<SIZE_LENGTH>(tag_id, val)?
            },
            Some(TagDataType::Integer) => {
                let val = tag.as_signed_int().unwrap_or_else(|| panic!("Bad specification implementation: Tag id {} type was integer, but could not get tag!", tag_id));
                self.write_signed_int_tag::<SIZE_LENGTH>(tag_id, val)?
            },
            Some(TagDataType::Utf8) => {
                let val = tag.as_utf8().unwrap_or_else(|| panic!("Bad specification implementation: Tag id {} type was utf8, but could not get tag!", tag_id));
                self.write_utf8_tag::<SIZE_LENGTH>(tag_id, val)?
            },
            Some(TagDataType::Binary) => {
                let val = tag.as_binary().unwrap_or_else(|| panic!("Bad specification implementation: Tag id {} type was binary, but could not get tag!", tag_id));
                self.write_binary_tag::<SIZE_LENGTH>(tag_id, val)?
            },
            Some(TagDataType::Float) => {
                let val = tag.as_float().unwrap_or_else(|| panic!("Bad specification implementation: Tag id {} type was float, but could not get tag!", tag_id));
                self.write_float_tag::<SIZE_LENGTH>(tag_id, val)?
            },
            Some(TagDataType::Master) => {
                let position = tag.as_master().unwrap_or_else(|| panic!("Bad specification implementation: Tag id {} type was master, but could not get tag!", tag_id));

                match position {
                    Master::Start => self.start_tag(tag_id, SIZE_LENGTH),
                    Master::End => self.end_tag(tag_id)?,
                    Master::Full(children) => {
                        self.start_tag(tag_id, SIZE_LENGTH);
                        for child in children {
                            self.write(child)?;
                        }
                        self.end_tag(tag_id)?;
                    }
                }
            },
            None => { // Should be a "raw tag"
                if !is_vint(tag_id) {
                    return Err(TagWriterError::TagIdError(tag_id));
                } else {
                    let val = tag.as_binary().unwrap_or_else(|| panic!("Bad specification implementation: Tag id {} type was raw tag, but could not get binary data!", tag_id));
                    self.write_binary_tag::<SIZE_LENGTH>(tag_id, val)?
                }
            }
        }

        if !self.open_tags.iter().any(|t| matches!(t.1, Known(_))) {
            self.private_flush()
        } else {
            Ok(())
        }
    }

    ///
    /// Write a tag with an unknown size to this instance's destination.
    /// 
    /// DEPRECATED - Prefer using the [`write_advanced()`](#method.write_advanced) method with [`WriteOptions`] obtained from their [`is_unknown_sized_element()`](struct.WriteOptions.html#method.is_unknown_sized_element) instead.
    /// 
    /// This method allows you to start a tag that doesn't have a known size.  Useful for streaming, or when the data is expected to be too large to fit into memory.  This method can *only* be used on Master type tags.
    /// 
    /// ## Errors
    /// 
    /// This method will return an error if the input tag is not a Master type tag, as those are the only types allowed to be of unknown size.
    /// 
    #[deprecated(since="0.6.0", note="Please use 'write_advanced' with WriteOptions obtained using 'is_unknown_sized_element' instead")]
    pub fn write_unknown_size<TSpec: EbmlSpecification<TSpec> + EbmlTag<TSpec> + Clone>(&mut self, tag: &TSpec) -> Result<(), TagWriterError> {
        let tag_id = tag.get_id();
        let tag_type = TSpec::get_tag_data_type(tag_id);
        match tag_type {
            Some(TagDataType::Master) => {},
            _ => {
                return Err(TagWriterError::TagSizeError(format!("Cannot write an unknown size for tag of type {tag_type:?}")))
            }
        };
        self.start_unknown_size_tag(tag_id);
        Ok(())
    }

    ///
    /// Write raw tag data to this instance's destination.
    ///
    /// This method allows writing any tag id with any arbitrary data without using a specification.  Specifications should generally provide an `Unknown` variant to handle arbitrary unknown data which can be written through the regular [`write()`](#method.write) method, so use of this method is typically discouraged.
    ///
    /// ## Errors
    /// 
    /// This method can error if there is a problem writing the input tag.  The different possible error states are enumerated in [`TagWriterError`].
    ///
    /// ## Examples
    ///
    /// ```no_run
    /// use std::fs::File;
    /// use ebml_iterable::TagWriter;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut file = File::create("my_ebml_file.ebml")?;
    /// let mut my_writer = TagWriter::new(&mut file);
    /// my_writer.write_raw(0x1a45dfa3, &[0x18, 0x53, 0x80, 0x67, 0x81, 0x01])?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    pub fn write_raw(&mut self, tag_id: u64, data: &[u8]) -> Result<(), TagWriterError> {
        self.write_binary_tag::<0>(tag_id, data)?;
        
        if !self.open_tags.iter().any(|t| matches!(t.1, Known(_))) {
            self.private_flush()
        } else {
            Ok(())
        }        
    }

    ///
    /// Attempts to flush all unwritten tags to the underlying destination.
    /// 
    /// This method can be used to finalize any open [`Master`] type tags that have not been ended.  The writer makes an attempt to close every open tag and write all bytes to the instance's destination.
    /// 
    /// ## Errors
    /// 
    /// This method can error if there is a problem writing to the destination.
    /// 
    pub fn flush(&mut self) -> Result<(), TagWriterError> {
        while let Some(id) = self.open_tags.last().map(|t| t.0) {
            self.end_tag(id)?;
        }
        self.private_flush()
    }

    //TODO: panic on drop if there is an open tag that hasn't been written.  Or maybe flush stream of any open tags?
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::super::tools::Vint;
    use super::TagWriter;

    #[test]
    fn write_ebml_tag() {
        let mut dest = Cursor::new(Vec::new());
        let mut writer = TagWriter::new(&mut dest);
        writer.write_raw(0x1a45dfa3, &[]).expect("Error writing tag");

        let zero_size = 0u64.as_vint().expect("Error converting [0] to vint")[0];
        assert_eq!(vec![0x1a, 0x45, 0xdf, 0xa3, zero_size], dest.get_ref().to_vec());
    }
}