demit 1.0.0

A flexible data generator for various domains
Documentation
use crate::error::Result;
use clap::ValueEnum;
use serde::Serialize;
use std::io::Write;

/// Supported output formats
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
pub enum OutputFormat {
    Json,
    Csv,
}

impl OutputFormat {
    /// Writes data in the specified format to the given writer
    pub fn write_data<W, T>(self, writer: W, data: &[T]) -> Result<()>
    where
        W: Write,
        T: Serialize,
    {
        match self {
            Self::Json => write_json(writer, data),
            Self::Csv => write_csv(writer, data),
        }
    }
}

/// Writes data as JSON
fn write_json<W: Write, T: Serialize>(mut writer: W, data: &[T]) -> Result<()> {
    let json_data = serde_json::to_string_pretty(data)?;
    writer.write_all(json_data.as_bytes())?;
    writer.write_all(b"\n")?;
    Ok(())
}

/// Writes data as CSV
fn write_csv<W: Write, T: Serialize>(writer: W, data: &[T]) -> Result<()> {
    let mut wtr = csv::Writer::from_writer(writer);
    for record in data {
        wtr.serialize(record)?;
    }
    wtr.flush()?;
    Ok(())
}