lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! The six local data carriers feed the same native source selection path.

mod numpy;
mod parquet;
mod text;

use std::path::Path;

use crate::Result;

use super::{
    bindings::BindingObject,
    codec::invalid,
    source::{expand_path, FileSource, NullValues},
};

pub(super) fn read<'a>(file: &FileSource, base: &Path) -> Result<BindingObject<'a>> {
    let path = expand_path(&file.path, base)?;
    read_path(file, &path).map_err(|error| error.with_input_path(&path))
}

fn read_path<'a>(file: &FileSource, path: &Path) -> Result<BindingObject<'a>> {
    let format = file
        .format
        .as_deref()
        .or_else(|| path.extension().and_then(|part| part.to_str()))
        .ok_or_else(|| invalid("data file needs an explicit format"))?
        .to_ascii_lowercase();
    let is_text = matches!(format.as_str(), "csv" | "tsv");
    if !is_text
        && (file.delimiter.is_some()
            || file.encoding.is_some()
            || file.has_header.is_some()
            || !file.schema.is_empty()
            || file.null_values != NullValues::None)
    {
        return Err(invalid("text reading options require CSV or TSV"));
    }
    let value = match format.as_str() {
        "csv" | "tsv" => text::csv(path, file, format == "tsv"),
        "json" => text::json(path),
        "npy" => std::fs::File::open(path)
            .map_err(crate::Error::from)
            .and_then(|file| numpy::npy(std::io::BufReader::new(file))),
        "npz" => numpy::npz(path),
        "parquet" => parquet::read(path),
        _ => Err(invalid(format!("unknown local data format {format:?}"))),
    }?;
    value.map_keys(&file.key_map)
}