lander/ltm/include/ltm/template.h

105 lines
3.0 KiB
C

#ifndef LTM_TEMPLATE
#define LTM_TEMPLATE
#include <stdlib.h>
#include "ltm/common.h"
/**
* Represents a compiled template
*/
typedef struct ltm_template ltm_template;
/**
* Compile the given template.
*
* @param out where to store pointer to newly allocated `ltm_template`
* @param template nul-terminated string containing the template
*/
ltm_err ltm_template_compile(ltm_template **out, const char *template);
/**
* Compile the given template with a given length.
*
* @param out where to store pointer to newly allocated `ltm_template`
* @param template char buffer containing the template
* @param len length of the char buffer
*/
ltm_err ltm_template_compile_n(ltm_template **out, const char *template,
size_t len);
/**
* Free the template instance. After freeing a template, no instances associated
* with it are safe to use.
*/
void ltm_template_free(ltm_template *template);
/**
* Represents a specific instance of a template.
*/
typedef struct ltm_instance ltm_instance;
typedef ltm_err (*ltm_data_fn)(size_t *written, char *buf, size_t len,
void *data);
/**
* Create a new instance of the given template.
*/
ltm_err ltm_template_instantiate(ltm_instance **out,
const ltm_template *template);
/**
* Free the given instance, as well as all nested instances.
*/
void ltm_instance_free(ltm_instance *instance);
typedef enum ltm_instance_block_type {
ltm_instance_block_type_buf = 0,
ltm_instance_block_type_buf_owned,
ltm_instance_block_type_file,
ltm_instance_block_type_file_owned,
ltm_instance_block_type_nested,
ltm_instance_block_type_fn,
} ltm_instance_block_type;
/**
* Add a new variable to the template.
*/
ltm_err ltm_instance_block_add_var(ltm_instance *instance, const char *name,
ltm_instance_block_type type, void *data,
size_t len);
/**
* Add a new variable to the template whose data is provided by a data function.
*/
ltm_err ltm_instance_block_add_var_fn(ltm_instance *instance, const char *name,
ltm_data_fn fn, void *data, size_t len);
/**
* Add a new nested instance to the instance, returning a handle to the nested
* instance.
*/
ltm_err ltm_instance_block_add_nested(ltm_instance **out,
ltm_instance *instance, const char *name);
/**
* Calculate the size of the resulting output of this instance.
*/
size_t ltm_instance_size(const ltm_instance *instance);
/**
* Write at most `len` bytes to the given buffer.
*
* @param written outputs how many bytes were written to `buf`
* @param buf buffer to write to
* @param len length of the buffer
* @param instance instance to write
* @return `ltm_err_ok` if write was successful but there's more to be written,
* `ltm_err_done` if everything has been written successfully, or some other
* error code
*/
ltm_err ltm_instance_write(size_t *written, char *buf, size_t len,
ltm_instance *instance);
#endif