ihb2032/MoonFrame/io does not have a README file

    ChartKind

    pub(all) enum ChartKind {
    Bar
    Line
    Point
    Area
    } derive(Eq,
    Debug
    )

    The mark type of a chart, mapped to a Vega-Lite top-level mark: Bar → "bar", Line → "line", Point → "point", Area → "area". pub(all) so callers can name the variants when building a ChartSpec (though the ChartSpec::bar / line / point / area constructors set the kind for you).

    ChartSpec

    pub struct ChartSpec {
    kind : ChartKind
    x : String
    y : String
    color : String?
    title : String?
    color_type : VegaType?
    } derive(Eq,
    Debug
    )

    A chart specification: the mark kind, the x / y encoding columns, an optional color grouping column, and an optional title. Fields are read-only outside the package — build a spec through one of the mark-named constructors (ChartSpec::bar(x, y) / line / point / area) and chain with_color(column) / with_title(text):

    ChartSpec::bar("region", "revenue").with_title("Revenue by region")

    x / y / color are column names resolved against the frame at format_vega_lite time (a missing name raises ColumnNotFound); each column's dtype decides its Vega-Lite field type (numeric → quantitative, otherwise → nominal), unless color_type overrides the color channel — e.g. a numeric grouping column (a cluster id) rendered as Nominal distinct colors rather than a continuous gradient.

    ChartSpec::area

    fn ChartSpec::area(x : String, y : String) -> ChartSpec

    An area chart of y against x (Vega-Lite mark: "area").

    ChartSpec::bar

    fn ChartSpec::bar(x : String, y : String) -> ChartSpec

    A bar chart of y against x (Vega-Lite mark: "bar").

    ChartSpec::line

    fn ChartSpec::line(x : String, y : String) -> ChartSpec

    A line chart of y against x (Vega-Lite mark: "line").

    ChartSpec::point

    fn ChartSpec::point(x : String, y : String) -> ChartSpec

    A scatter (point) chart of y against x (Vega-Lite mark: "point").

    ChartSpec::with_color

    fn ChartSpec::with_color(self : ChartSpec, column : String) -> ChartSpec

    Return a copy of this spec that maps column to the Vega-Lite color encoding (grouping / colouring the marks by that column). Chainable.

    ChartSpec::with_color_type

    fn ChartSpec::with_color_type(self : ChartSpec, color_type : VegaType) -> ChartSpec

    Return a copy of this spec that overrides the color channel's Vega-Lite field type, instead of inferring it from the column dtype. Use Nominal (or Ordinal) to render a numeric grouping column — a cluster id, a year — as distinct per-group colors rather than the continuous gradient that quantitative (the numeric default) would produce. Only the color channel honours this; x / y keep dtype inference. Chainable.

    ChartSpec::with_title

    fn ChartSpec::with_title(self : ChartSpec, title : String) -> ChartSpec

    Return a copy of this spec carrying the chart title. Chainable.

    CsvReadOptions

    pub(all) struct CsvReadOptions {
    has_header : Bool
    delimiter : Char
    infer_schema_rows : Int
    null_values : Array[String]
    strict_column_count : Bool
    on_parse_error : OnParseError
    allow_nonfinite_floats : Bool
    }

    Options that control how a CSV input is parsed into a DataFrame.

    • has_header — when true, the first row supplies column names. When false, every row is treated as data and column names are synthesised as "column1", "column2", … in declaration order; the first data row fixes the column count, so a later wider row's trailing cells are dropped under the lenient default (set strict_column_count = true to reject a ragged row instead).
    • delimiter — field separator passed through to NyaCSV.
    • infer_schema_rows — number of leading rows scanned when guessing each column's dtype. 0 (or any value <= 0) lifts the cap and scans every row (Polars' infer_schema_length=None), trading a slower inference pass for never mis-guessing a column from a prefix. Cells past a finite window are still parsed under the chosen dtype; one that doesn't fit is handled per on_parse_error.
    • null_values — raw strings that should be treated as null cells (both for type inference, which skips them, and for the final typed column, where they become None). The default [""] matches the empty string only, which is how an absent CSV cell is typically represented.
    • strict_column_count — when true, every data row must have exactly as many cells as the header declares; a ragged row (too few or too many cells) raise ParseError instead of being silently null-padded (short row) or truncated (long row). Defaults to false, preserving the lenient behaviour that tolerates ragged rows (a permissive CSV idiom, and what the v0.1 reader did).
    • on_parse_error — what to do when a non-null cell past the inference window fails to parse under its column's locked-in dtype. Raise (default) fails the whole read with ParseError; Null downgrades the offending cell to a null cell and keeps the column's inferred dtype (Polars' ignore_errors=True). See OnParseError.
    • allow_nonfinite_floats — when true (default), the float probe accepts the nan / inf / infinity literals @string.parse_double recognises, so a column of those tokens infers as Float. When false, the probe rejects them, so such a column falls back to String instead of being silently retyped to Float (a non-finite token past the window is then a parse failure handled per on_parse_error).

    CsvReadOptions::default

    Default read options: header on, comma delimiter, scan the first 100 rows for inference, treat the empty string as null, tolerate ragged rows (strict_column_count = false), fail the read on a cell that doesn't fit its inferred dtype (on_parse_error = Raise), and accept non-finite float literals (allow_nonfinite_floats = true).

    CsvWriteOptions

    pub(all) struct CsvWriteOptions {
    header : Bool
    delimiter : Char
    null_value : String
    }

    Options that control how a DataFrame is rendered as CSV text.

    • header — when true, the first emitted row is the column names; when false, only data rows are written.
    • delimiter — field separator written between cells.
    • null_value — the literal string written in place of a null cell. The default empty string round-trips with the reader's default null_values.

    CsvWriteOptions::default

    Default write options: header on, comma delimiter, null cells emitted as the empty string.

    JsonReadOptions

    pub(all) struct JsonReadOptions {
    infer_schema_rows : Int
    on_parse_error : OnParseError
    }

    Options that control how a JSON records payload is parsed into a DataFrame.

    • infer_schema_rows — number of leading records inspected when guessing each column's dtype. 0 (or any value <= 0) lifts the cap and scans every record (Polars' infer_schema_length=None). Records past a finite window are still parsed under the chosen dtype; one that doesn't fit is handled per on_parse_error.
    • on_parse_error — what to do when a non-null cell past the inference window fails to parse under its column's locked-in dtype: Raise (default) fails the whole read with ParseError; Null downgrades the offending cell to a null and continues (Polars' ignore_errors=True). See OnParseError.

    JsonReadOptions::default

    Default read options: scan the first 100 records for inference and fail the read on a cell that doesn't fit its inferred dtype (on_parse_error = Raise).

    NdjsonReadOptions

    pub(all) struct NdjsonReadOptions {
    infer_schema_rows : Int
    on_parse_error : OnParseError
    }

    Options that control how an NDJSON payload is parsed into a DataFrame.

    • infer_schema_rows — number of leading records inspected when guessing each column's dtype. 0 (or any value <= 0) lifts the cap and scans every record (Polars' infer_schema_length=None). Records past a finite window are still parsed under the chosen dtype; one that doesn't fit is handled per on_parse_error.
    • on_parse_error — what to do when a non-null cell past the inference window fails to parse under its column's locked-in dtype: Raise (default) fails the whole read with ParseError; Null downgrades the offending cell to a null and continues (Polars' ignore_errors=True). See OnParseError.

    (Same meanings and defaults as JsonReadOptions / the CSV reader — NDJSON keeps its own options type so the two formats can diverge later.)

    NdjsonReadOptions::default

    Default read options: scan the first 100 records for inference and fail the read on a cell that doesn't fit its inferred dtype (on_parse_error = Raise).

    OnParseError

    pub(all) enum OnParseError {
    Raise
    Null
    } derive(Eq,
    Debug
    )

    What a reader does when a non-null cell fails to parse under the dtype that inference locked in for its column — in practice a value past the inference window that doesn't fit (e.g. a String in a column inferred Int from its first rows).

    • Raise (every reader's default) — surface the cell's ParseError, failing the whole read. The strict, lossless behaviour: a malformed cell is never silently dropped.
    • Null — downgrade the offending cell to a null cell and keep going, the resilient behaviour Polars exposes as ignore_errors=True (pandas tolerates the same). The column keeps its inferred dtype; only the unparseable cells become null.

    Shared by CsvReadOptions / JsonReadOptions / NdjsonReadOptions and consumed in build_typed_column's parse-failure branch, so the three readers agree on the policy.

    VegaType

    pub(all) enum VegaType {
    Quantitative
    Nominal
    Ordinal
    Temporal
    } derive(Eq,
    Debug
    )

    A Vega-Lite field type, used to override the dtype-based inference for the color channel. pub(all) so callers can name the variants when calling with_color_type. Quantitative is a continuous measure (a color gradient), Nominal an unordered category (distinct colors per value), Ordinal an ordered category, and Temporal a time field.

    format_csv

    Render a DataFrame as a CSV string.

    • Header (when options.header == true): column names joined by options.delimiter, each quoted only when it would otherwise be ambiguous.
    • Each row: cells joined by options.delimiter, terminated by \n (LF). Null cells are written as options.null_value; other cells render via Scalar::to_string.
    • Quoting: a cell containing the delimiter, a double quote, \r, or \n is wrapped in double quotes; interior double quotes are doubled (" → ""). Cells that need no quoting are written verbatim so the output matches the simple "no quotes" CSV idiom whenever possible. The lone exception: in a single-column frame an empty cell (or an empty column name) is written as "" rather than a bare blank, so the row is not a blank line the reader would skip.
    • Round-trip caveat: cells render via Scalar::to_string, so a Float whose value is a whole number is written without a fractional part (2.0 → 2) and is re-inferred as Int on read — the same dtype narrowing the JSON writer documents. A String cell with significant leading / trailing whitespace is written bare (only the delimiter, a quote, \r, or \n force quoting), so this reader round-trips it (trim_spaces off), but an RFC-4180 consumer that trims surrounding whitespace may drop it. A String cell whose text equals a reader null token — the default null_value is the empty string "", so this includes empty strings, plus any custom null_values entry — is read back as null and cannot be distinguished from a true null. A String cell whose text parses as another dtype is likewise re-inferred on read: inference is content-based with no header type hints, so a column of numeric-looking strings ("01", "2") returns as Int / Float — dropping any leading zeros — and "true" / "false" as Bool, the dtype-from-content narrowing inherent to typeless CSV (matching Polars' read_csv). Quote / escape handling is otherwise round-trip safe.
    • Raises InvalidOperation if options.delimiter is a double quote or a line terminator (\n / \r): those collide with the hard-coded quote character and the row terminator, so no escaping could make the output frame fields unambiguously (see validate_csv_delimiter).

    format_json_records

    fn format_json_records(df :
    DataFrame
    ) -> String

    Render a DataFrame as a JSON records string [ {...}, ... ].

    Per cell:
    • Null → JSON null
    • Int → JSON number (no fractional part)
    • Float→ JSON number for finite values. NaN / ±Infinity have no JSON literal, so they are emitted as null (matching pandas' to_json) to keep the output valid JSON — a round-trip reads a non-finite cell back as a null.
    • Bool → JSON true / false
    • String → JSON string (escaping ", \, control chars via the builtin stringifier — we deliberately do not roll our own escape so any future Unicode spec tweaks land transparently)

    Keys appear in the column declaration order, preserved by the builtin Map (linked-hash-map) used for each record object.

    format_ndjson

    fn format_ndjson(df :
    DataFrame
    ) -> String

    Render a DataFrame as an NDJSON string: one flat JSON object per row, each terminated by \n (including the last, matching the CSV writer's per-row LF and Polars' write_ndjson). A 0-row frame renders the empty string.

    Per-cell conventions are shared with format_json_records via scalar_to_json: Null → null; Int → JSON number (exact up to ±2^53); finite Float → JSON number, non-finite (NaN / ±Infinity) → null so each line stays valid JSON; Bool → true / false; String → escaped JSON string. Keys appear in df.columns() order, preserved by the linked-hash-map Map backing each record object.

    format_vega_lite

    Render df and spec as a complete Vega-Lite v5 specification JSON string: $schema (pinned to the Vega-Lite v5 schema URL) + optional title + mark (from spec.kind) + encoding (x / y and, when set, color, each {field, type} with the type inferred from the column dtype: numeric → "quantitative", otherwise → "nominal") + data.values (the frame inlined as JSON records, sharing format_json_records' cell mapping — null and non-finite-float cells become JSON null). A frame with the encoded columns but zero rows yields "data":{"values":[]}.

    The spec's x / y / color columns are resolved left-to-right; the first name absent from df raises ColumnNotFound(name) — this is the one reason the function is not total (it accepts column names, and a name can be wrong). The emitted text is always valid JSON (it is built through @json and stringified), so it round-trips through any standards-compliant JSON / Vega-Lite reader.

    parse_csv_str

    Parse a CSV-encoded string into a DataFrame. The pipeline is:
    1. NyaCSV tokenises the text into headers + rows. NyaCSV always treats the first row as a header, so the has_header = false case re-folds that row into the data section and synthesises column1, column2, … names.
    2. Per-column type inference walks the first infer_schema_rows rows in order Int → Float → Bool → String (a null cell within them is skipped but still counts toward the window). The first option that accepts every probed cell wins; a column with no non-null probes lands on String (no information to disambiguate).
    3. Null mapping replaces any raw cell whose verbatim string sits in null_values with None. The mapping runs after tokenisation, so quoted empty cells ("") and bare empty cells are both honoured.
    4. Each column is assembled into a typed Series and the result is wrapped through DataFrame::new.

    Raises:
    • DuplicateColumn(name) — two headers share a name.
    • ParseError(...) — a non-null cell does not parse under the inferred dtype for its column (typically because a sample row outside the inference window is malformed for the inferred type), unless options.on_parse_error is Null, which downgrades that cell to a null instead of failing the read; or — when options.strict_column_count is true — a data row's cell count differs from the header's (reported as row N: expected C columns,got G, 1-based over the data rows).
    • Whatever DataFrame::new propagates — for v0.1 this is limited to DuplicateColumn / LengthMismatch, neither of which can actually fire here (uniqueness is checked above; every column is built off the same rows.length()).

    Limitation: tokenisation is delegated to NyaCSV, whose quote handling is lenient and never raises a ParseError for a malformed quote. An unterminated quoted field at end-of-input is read as a complete field (1,"unclosed → last cell unclosed); text after a closing quote is folded into the same field ("ab"cd → abcd); and a lone quote inside an unquoted field is kept literally (ab"cd → ab"cd). A strict RFC-4180 reader rejects all three; MoonFrame accepts them, and no quote-balance pre-scan is performed.

    parse_json_records_str

    Parse a JSON records string ([ {...}, ... ]) into a DataFrame.

    @json.parse produces the Json AST; a top-level value that is not an array surfaces as ParseError. The array's elements are then handed to frame_from_json_records, which validates each is an object, collects headers in first-seen order across all records, infers one dtype per column, and materialises the frame (see that helper for the per-column rules). An empty array — like empty or whitespace-only input — yields a 0×0 frame.

    Raises:
    • ParseError(...) — malformed JSON, a top-level value that is not an array, a record that is not an object, or a non-null cell that does not fit the column's inferred dtype (the last unless options.on_parse_error is Null, which downgrades that cell to a null instead of failing the read).
    • Whatever DataFrame::new propagates (duplicate-header is pre-empted upstream; length-mismatch cannot fire because every column is built off records.length()).

    parse_ndjson_str

    Parse an NDJSON string (one JSON object per line) into a DataFrame.

    Pipeline:
    1. Split content on \n. Each non-blank line is parsed with @json.parse; a malformed line surfaces as ParseError("line N: ...") (1-based). Blank / whitespace-only lines are skipped, so the writer's trailing newline — and any incidental blank lines — never produce phantom records.
    2. The parsed values are handed to frame_from_json_records, which validates each is an object, collects headers in first-seen order across all records (sparse records → null cells), infers one dtype per column, and materialises the frame (see that helper, shared with parse_json_records_str, for the per-column rules).

    Empty input — or input that is entirely blank lines — yields a 0×0 frame, matching parse_json_records_str's empty-array behaviour.

    Raises:
    • ParseError(...) — a malformed line, a line whose value is not a JSON object, or a non-null cell that does not fit its column's inferred dtype (the last unless options.on_parse_error is Null, which downgrades that cell to a null instead).
    • Whatever DataFrame::new propagates.

    read_csv

    Read a CSV file using the default options.

    read_csv_projected

    fn read_csv_projected(path : String, options : CsvReadOptions, projection : Array[String]) ->
    DataFrame
    raise
    DataError

    Read a CSV file, building only the columns named in projection — the file-backed entry behind the lazy scan_csv source's projection pushdown. Identical to read_csv_with_options except that a column whose header name is not in projection is never inferred, parsed, or materialised (see parse_csv_str_projected for the precise contract, including the one behavioural consequence: a parse error confined to a dropped column does not surface). IOError from the file system surfaces as raise IoError(message).

    read_csv_with_options

    Read a CSV file with custom options. IOError from the file system surfaces as raise IoError(message).

    read_json

    Read a JSON records file using the default options.

    read_json_with_options

    Read a JSON records file with custom options. Filesystem errors surface as raise IoError(message).

    read_ndjson

    Read an NDJSON file using the default options.

    read_ndjson_projected

    fn read_ndjson_projected(path : String, options : NdjsonReadOptions, projection : Array[String]) ->
    DataFrame
    raise
    DataError

    Read an NDJSON file, building only the columns named in projection — the file-backed entry behind the lazy scan_ndjson source's projection pushdown. Identical to read_ndjson_with_options except that a column whose header name is not in projection is never inferred or built (see frame_from_json_records for the precise contract, including the one behavioural consequence: a parse error confined to a dropped column does not surface). Filesystem errors surface as raise IoError(message).

    read_ndjson_with_options

    Read an NDJSON file with custom options. Filesystem errors surface as raise IoError(message).

    write_csv

    Write a DataFrame to a CSV file using the default options.

    write_csv_with_options

    fn write_csv_with_options(path : String, df :
    DataFrame
    , options : CsvWriteOptions) -> Unit raise
    DataError

    Write a DataFrame to a CSV file with custom options. IOError from the file system surfaces as raise IoError(message).

    write_json_records

    fn write_json_records(path : String, df :
    DataFrame
    ) -> Unit raise
    DataError

    Write a DataFrame to a JSON records file. Filesystem errors surface as raise IoError(message).

    write_ndjson

    Write a DataFrame to an NDJSON file. Filesystem errors surface as raise IoError(message).

    write_vega_lite

    fn write_vega_lite(path : String, df :
    DataFrame
    , spec : ChartSpec) -> Unit raise
    DataError

    Write a Vega-Lite v5 spec for df / spec to path. Mirrors write_json_records: a ColumnNotFound from format_vega_lite (a spec column absent from df) propagates unchanged, and a filesystem failure surfaces as raise IoError(message).