Understanding how to add functionnality

⚓ Rust    📅 2025-06-27    👤 surdeus    👁️ 7      

surdeus

Warning

This post was published 43 days ago. The information described in this article may have changed.

Hi,

I am working on a document generator using Typst.
I use the typst_as_lib - Rust

I want to create a generic document generator so I was thinking to use mutiple Hasmap to init data before generation.

But it seems that Hashmap is not implemented for a trait.

I was thinking to use some vec in place... that I can init from Hashmap.
But maybe, I also can extends the missing functionnalities. As it appears to use a Macro, I have some problem to undestand how to take in account HashMap data ?

Can you help me a little on the way please ?

I make a example that works (without hashmap). Then I try to make a more generic structure like that :

use derive_typst_intoval::{IntoDict, IntoValue};
use std::{collections::HashMap, fs};
use typst::foundations::{Bytes, Dict, IntoValue};
use typst_as_lib::TypstEngine;

//static FONT: &[u8] = include_bytes!("./fonts/texgyrecursor-regular.ttf");

#[derive(Debug, Clone)]
pub enum TemplateFile {
    Document1 ,
}

impl TemplateFile {
    pub fn as_filename(&self) -> &'static str {
        match self {
            TemplateFile::Document1 => include_str!("./template.typ"),
        }
    }
}

#[derive(Debug, Clone, IntoValue, IntoDict)]
pub struct GenerateDocument {
   /* If hashmap is not possible
    data_keys: Option<Vec<String>>,
    data_values: Option<Vec<String>>,

    vec_string_keys: Option<Vec<String>>,
    vec_string_values: Option<Vec<Vec<String>>>,

    vec_number_keys: Option<Vec<String>>,
    vec_number_values: Option<Vec<Vec<f64>>>,

    vec_img_keys: Vec<String>,
    vec_img_values: Vec<Option<Bytes>>,
*/
    datas: HashMap<String, String>,
//  numbers: HashMap<String, f64>, ...
}

impl GenerateDocument {
  /*  fn init_values(&self, values: HashMap<String, String>) {
        for (key, value) in values {
            self.data_keys.push(key);
            self.data_values.push(value);
        }
    }*/

    fn generate_document(&self, template: TemplateFile, output_filename: &str) {
        let template = TypstEngine::builder()
            .main_file(template.as_filename())
            // .fonts([FONT])
            .build();

        // Run it
        let doc = template
            .compile_with_input(self.clone())
            .output
            .expect("typst::compile() returned an error!");

        // Create pdf
        let options = Default::default();
        let pdf = typst_pdf::pdf(&doc, &options).expect("Could not generate pdf.");
        fs::write(output_filename, pdf).expect("Could not write pdf.");
    }
}

impl From<GenerateDocument> for Dict {
    fn from(value: GenerateDocument) -> Self {
        value.into_dict()
    }
}

The problem is about the last impl with Dict...

1 post - 1 participant

Read full topic

🏷️ rust_feed