uneval/
funcs.rs

1//! Convenience functions to be used with Uneval.
2
3use crate::error::UnevalError;
4use crate::ser::{SerResult, Uneval};
5use serde::Serialize;
6
7/// Write generated Rust code to the provided [`Write`][std::io::Write] implementation.
8pub fn write(value: impl Serialize, target: impl std::io::Write) -> SerResult {
9    value.serialize(&mut Uneval::new(target))
10}
11
12/// Writes generated Rust code to file.
13///
14/// This is probably the most common way to use `uneval`. When Cargo runs your crate's build task,
15/// it sets the `OUT_DIR` environment variable to the path to build target directory (see
16/// [Cargo reference](https://doc.rust-lang.org/cargo/reference/environment-variables.html) for more).
17/// So, you can use it in two steps:
18/// 1. Generate the Rust code and write it to temporary file:
19/// ```no_run
20/// # let value = ();
21/// let path: std::path::PathBuf = [
22///     std::env::var("OUT_DIR").expect("No build target path set"),
23///     "file_name.rs".into()
24/// ].iter().collect();
25/// uneval::to_file(value, path).expect("Write failed");
26/// ```
27/// 2. [Include][include] the generated Rust code wherever it is needed:
28/// ```ignore
29/// let value = include!(concat!(env!(OUT_DIR), "/file_name.rs"));
30/// ```
31///
32/// [include]: https://doc.rust-lang.org/stable/std/macro.include.html
33pub fn to_file(value: impl Serialize, target: impl AsRef<std::path::Path>) -> SerResult {
34    value.serialize(&mut Uneval::new(std::fs::File::create(target)?))
35}
36
37/// Convenience wrapper around [`to_file`].
38///
39/// This function finds out where the output directory is by looking at `OUT_DIR` environment variable
40/// and creates the file with the provided name there.
41pub fn to_out_dir(value: impl Serialize, file_name: impl AsRef<str>) -> SerResult {
42    let path: std::path::PathBuf = [
43        std::env::var("OUT_DIR")
44            .expect("OUT_DIR not set, check if you're running this from the build script"),
45        file_name.as_ref().into(),
46    ]
47    .iter()
48    .collect();
49    value.serialize(&mut Uneval::new(std::fs::File::create(path)?))
50}
51
52/// Obtain string with generated Rust code.
53pub fn to_string(value: impl Serialize) -> Result<String, UnevalError> {
54    let mut out = Vec::new();
55    value.serialize(&mut Uneval::new(&mut out))?;
56    Ok(String::from_utf8(out)?)
57}