fuels_rs/code_gen/
bindings.rs

1use crate::errors::Error;
2use crate::rustfmt;
3use proc_macro2::TokenStream;
4use std::{fs::File, io::Write, path::Path};
5
6/// Type-safe contract bindings generated by a `Builder`. This type can be
7/// either written to file or into a token stream for use in a procedural macro.
8pub struct ContractBindings {
9    /// The TokenStream representing the contract bindings.
10    pub tokens: TokenStream,
11    /// The output options used for serialization.
12    pub rustfmt: bool,
13}
14
15impl ContractBindings {
16    /// Writes the bindings to a given `Write`.
17    pub fn write<W>(&self, mut w: W) -> Result<(), Error>
18    where
19        W: Write,
20    {
21        let source = {
22            let raw = self.tokens.to_string();
23
24            if self.rustfmt {
25                rustfmt::format(&raw).unwrap_or(raw)
26            } else {
27                raw
28            }
29        };
30
31        w.write_all(source.as_bytes()).unwrap();
32        Ok(())
33    }
34
35    /// Writes the bindings to the specified file.
36    pub fn write_to_file<P>(&self, path: P) -> Result<(), Error>
37    where
38        P: AsRef<Path>,
39    {
40        let file = File::create(path).unwrap();
41        self.write(file)
42    }
43
44    /// Converts the bindings into its underlying token stream. This allows it
45    /// to be used within a procedural macro.
46    pub fn into_tokens(self) -> TokenStream {
47        self.tokens
48    }
49}