Skip to main content

snix_serde/
lib.rs

1//! `snix-serde` bridges Rust types and [`snix_eval::Value`] via the
2//! standard [`serde`] traits, making it straightforward to use Nix as a
3//! configuration language.
4//!
5//! # Entry points
6//!
7//! | Function | Direction |
8//! |---|---|
9//! | [`from_str`] | Evaluate a Nix expression string → `T` |
10//! | [`from_value`] | [`snix_eval::Value`] → `T` |
11//! | [`to_value`] | `T` → [`snix_eval::Value`] |
12//!
13//! # Type mapping
14//!
15//! | Rust / serde | Nix |
16//! |---|---|
17//! | `bool` | `true` / `false` |
18//! | integers (`i8`…`i64`, `u8`…`u32`) | integer |
19//! | `u64` | integer (errors if > `i64::MAX`) |
20//! | `f32`, `f64` | float |
21//! | `char`, `str`, `String` | string |
22//! | `Option::None` / unit / unit struct | `null` |
23//! | `Option::Some(v)` / newtype struct | inner value |
24//! | sequence / tuple | list `[ … ]` |
25//! | map / struct | attribute set `{ … }` |
26//! | unit enum variant | string of the variant name |
27//! | newtype enum variant | `{ VariantName = value; }` |
28//! | tuple enum variant | `{ VariantName = [ … ]; }` |
29//! | struct enum variant | `{ VariantName = { … }; }` |
30//!
31//! Bytes are not supported by the Nix value model and will produce an error.
32//!
33//! # Examples
34//!
35//! Deserialise a Nix expression:
36//!
37//! ```rust
38//! # use serde::Deserialize;
39//! #[derive(Deserialize)]
40//! struct Config { host: String, port: u16 }
41//!
42//! let cfg: Config = snix_serde::from_str(r#"{ host = "localhost"; port = 8080; }"#).unwrap();
43//! assert_eq!(cfg.host, "localhost");
44//! assert_eq!(cfg.port, 8080);
45//! ```
46//!
47//! Serialise to a [`snix_eval::Value`] and back:
48//!
49//! ```rust
50//! # use serde::{Serialize, Deserialize};
51//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
52//! struct Point { x: i64, y: i64 }
53//!
54//! let p = Point { x: 1, y: 2 };
55//! let value = snix_serde::to_value(&p).unwrap();
56//! let q: Point = snix_serde::from_value(value).unwrap();
57//! assert_eq!(p, q);
58//! ```
59#![cfg_attr(docsrs, feature(doc_cfg))]
60
61mod de;
62mod error;
63mod ser;
64
65pub use de::from_str;
66pub use de::from_str_with_config;
67pub use de::from_value;
68pub use error::Error;
69pub use ser::to_string;
70pub use ser::to_value;
71
72#[cfg(test)]
73mod de_tests;
74#[cfg(test)]
75mod ser_tests;