lib/process/post.rs
1//! Defines the post-processor type.
2//!
3//! Post-processors are used mutate fields within a [`Render`].
4
5use crate::render::template::Render;
6use crate::strings;
7
8/// A struct for post-processing [`Render`]s.
9#[derive(Debug, Clone, Copy)]
10pub struct PostProcessor;
11
12impl PostProcessor {
13 /// Runs all post-strings on an [`Render`].
14 ///
15 /// # Arguments
16 ///
17 /// * `renders` - The [`Render`]s to process.
18 /// * `options` - The post-process options.
19 pub fn run<O>(renders: Vec<&mut Render>, options: O)
20 where
21 O: Into<PostProcessOptions>,
22 {
23 let options: PostProcessOptions = options.into();
24
25 for render in renders {
26 if options.trim_blocks {
27 Self::trim_blocks(render);
28 }
29
30 if let Some(width) = options.wrap_text {
31 Self::wrap_text(render, width);
32 }
33 }
34 }
35
36 /// Trims any blocks left after rendering.
37 ///
38 /// # Arguments
39 ///
40 /// * `render` - The [`Render`] to process.
41 fn trim_blocks(render: &mut Render) {
42 render.contents = strings::trim_blocks(&render.contents);
43 }
44
45 /// Wraps text to a maximum character width.
46 ///
47 /// Maximum line length is not guaranteed as long words are not broken if
48 /// their length exceeds the maximum. Hyphenation is not used, however,
49 /// an existing hyphen can be split on to insert a line-break.
50 ///
51 /// # Arguments
52 ///
53 /// * `render` - The [`Render`] to process.
54 /// * `width` - The maximum character width.
55 fn wrap_text(render: &mut Render, width: usize) {
56 let options = textwrap::Options::new(width).break_words(false);
57 render.contents = textwrap::fill(&render.contents, options);
58 }
59}
60
61/// A struct representing options for the [`PostProcessor`] struct.
62#[derive(Debug, Default, Clone, Copy)]
63pub struct PostProcessOptions {
64 /// Toggles trimming blocks left after rendering.
65 pub trim_blocks: bool,
66
67 /// Toggles wrapping text to a maximum character width.
68 pub wrap_text: Option<usize>,
69}