about summary refs log tree commit diff
path: root/tvix/serde/examples/cfg-demo.rs
diff options
context:
space:
mode:
authorVincent Ambo <mail@tazj.in>2023-01-28T10·45+0300
committertazjin <tazjin@tvl.su>2023-01-31T13·11+0000
commit4da1e64c030fc9b1bb23f1ef90546a531b5f760e (patch)
tree2a5d85f927faa4e1dc3909d88a0f9719a26e6429 /tvix/serde/examples/cfg-demo.rs
parent7702941dd9f561cb1f90ada28aa7401ea54a86db (diff)
feat(tvix/serde): add an example application to the project r/5785
This shows how people can use tvix_serde to deserialise configuration
structs for their programs from Nix code.

Change-Id: I71bf4e03dce19dddafe67dd729b4e4b10719a739
Reviewed-on: https://cl.tvl.fyi/c/depot/+/7945
Reviewed-by: flokli <flokli@flokli.de>
Tested-by: BuildkiteCI
Diffstat (limited to 'tvix/serde/examples/cfg-demo.rs')
-rw-r--r--tvix/serde/examples/cfg-demo.rs34
1 files changed, 34 insertions, 0 deletions
diff --git a/tvix/serde/examples/cfg-demo.rs b/tvix/serde/examples/cfg-demo.rs
new file mode 100644
index 000000000000..8d31c9fb0450
--- /dev/null
+++ b/tvix/serde/examples/cfg-demo.rs
@@ -0,0 +1,34 @@
+//! This program demonstrates how to use tvix_serde to deserialise
+//! program configuration (or other data) from Nix code.
+//!
+//! This makes it possible to use Nix as an embedded config language.
+//! For greater control over evaluation, and for features like adding
+//! additional builtins, depending directly on tvix_eval would be
+//! required.
+use serde::Deserialize;
+use std::collections::HashMap;
+
+#[derive(Debug, Deserialize)]
+enum Flavour {
+    Tasty,
+    Okay,
+    Eww,
+}
+
+#[derive(Debug, Deserialize)]
+struct Data {
+    name: String,
+    foods: HashMap<String, Flavour>,
+}
+
+fn main() {
+    // Get the content from wherever, read it from a file, receive it
+    // over the network - whatever floats your boat! We'll include it
+    // as a string.
+    let code = include_str!("foods.nix");
+
+    // Now you can use tvix_serde to deserialise the struct:
+    let foods: Data = tvix_serde::from_str(code).expect("deserialisation should succeed");
+
+    println!("These are the foods:\n{:#?}", foods);
+}