1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
/*! # beard In opposition to [mustache]. Here the goal instead of mustache is to leverage as much as possible rust's type system to detect error case and therefor to make the rendering deterministic. If you are looking for something that is going to be portable outside of rust you should checkout [mustache]. [`beard`] is a macro that will generate the necessary rust code to serialise the given _template_. You can achieve the same thing by writing the code yourself (calling [std::io::Write] appropriate methods). [`beard`] is simply an help to do that and to make it easier to maintain the templates. # How it works ## string literals Any string literal will be written as is in the output. ``` use beard::beard; # use std::io::Write as _; # # fn render() -> Result<String, std::io::Error> { # let mut output = Vec::new(); beard! { output, "List of items:\n" "\n" "* item 1\n" "* item 2\n" }; # Ok(String::from_utf8(output).unwrap()) # } # let output = render().unwrap(); ``` ## serialising any impl of Display You can intersperse serialised object that implements [`std::fmt::Display`], just use the curly bracket as you would if you were to use in [`std::format`] macro, except outside of the string. Interestingly it can also do any kind of operations within the brackets so long it returns something that implements [`std::fmt::Display`]. ``` use beard::beard; # use std::io::Write as _; # # fn render() -> Result<String, std::io::Error> { # let mut output = Vec::new(); let value = 42; beard! { output, { value } "\n" { 1 + 2 } "\n" }; # Ok(String::from_utf8(output).unwrap()) # } # let output = render().unwrap(); ``` ## serialising array of bytes In case the value is already an array and there is no need to run [`std::fmt::Display`]'s formatting to [`String`] as intermediate. ``` use beard::beard; # use std::io::Write as _; # # fn render() -> Result<String, std::io::Error> { # let mut output = Vec::new(); let value = b"some array"; beard! { output, [{ value }] "\n" }; # Ok(String::from_utf8(output).unwrap()) # } # let output = render().unwrap(); ``` ## Calling function to serialize Would you need to perform some operation with the [`std::io::Write`] object you can capture the variable by calling a _lambda_ (it's not really one). ``` use beard::beard; # use std::io::Write as _; # # fn render() -> Result<String, std::io::Error> { # let mut output = Vec::new(); let value = b"some array"; beard! { output, || { // do other operations output.write_all(b"some bytes")?; } }; # Ok(String::from_utf8(output).unwrap()) # } # let output = render().unwrap(); ``` ## `if` and `if let` statement There are times where one needs to serialize or not some parts. ``` use beard::beard; # use std::io::Write as _; # # fn render() -> Result<String, std::io::Error> { # let mut output = Vec::new(); let value = false; let optional = Some("something"); beard! { output, if (value) { "Value is true\n" } else { "Value is false\n" } "Or do some pattern matching\n" if let Some(value) = (optional) { "We have " { value } "\n" } }; # Ok(String::from_utf8(output).unwrap()) # } # let output = render().unwrap(); ``` ## `for` loop, iterating on items Shall you need to print the items of a list or anything that implements [`std::iter::IntoIterator`]. ``` use beard::beard; # use std::io::Write as _; # # fn render() -> Result<String, std::io::Error> { # let mut output = Vec::new(); let shopping_list = ["apple", "pasta", "tomatoes", "garlic", "mozzarella"]; beard! { output, "Shopping list\n" "\n" for (index, item) in (shopping_list.iter().enumerate()) { {index} ". " { item } "\n" } }; # Ok(String::from_utf8(output).unwrap()) # } # let output = render().unwrap(); ``` # Example ``` use beard::beard; # use std::io::Write as _; # # fn render() -> Result<String, std::io::Error> { let name = "Arthur"; let list = ["Bubble Bath", "Unicorn Crunchy Oat"]; # let mut output = Vec::new(); beard! { output, "Hi " { name } "\n" "\n" "Confirmation order about the following items:\n" for item in ( list ) { " * " { item } "\n" } "\n" "Your order will be ship to you once everything is ready.\n" }; # Ok(String::from_utf8(output).unwrap()) # } # let output = render().unwrap(); ``` The Example below will generate a string in the `output`: ```text Hi Arthur Confirmation order about the following items: * Bubble Bath * Unicorn Crunch Oat Your order will be ship to you once everything is ready. ``` [`beard`]: ./macro.beard.html [mustache]: https://mustache.github.io/mustache.5.html */ /// macro to call to generate the function stream of generating /// formatted output. /// /// The difference here with [`std::fmt::format`] is that instead /// generating a string based on some formatting parameters /// the [`beard`] macro generates a string based on the declarative /// flow. #[macro_export] macro_rules! beard { ($($any:tt)*) => { $crate::beard_internal!($($any)*); }; } /// use this internal macro to hide the details of the macro away /// /// this is not really useful for the user documentation anyway. #[macro_export] #[doc(hidden)] macro_rules! beard_internal { ($output:ident, ) => { }; ($output:ident, | | $statement:block $($any:tt)*) => { { $statement } $crate::beard_internal!($output, $($any)*); }; ($output:ident, || $statement:block $($any:tt)*) => { { $statement } $crate::beard_internal!($output, $($any)*); }; ($output:ident, $text:literal $($any:tt)*) => { $output.write_all($text.as_bytes())?; $crate::beard_internal!($output, $($any)*); }; ($output:ident, [ $statement:block ] $($any:tt)*) => { $output.write_all( $statement.as_ref() )?; $crate::beard_internal!($output, $($any)*); }; ($output:ident, $statement:block $($any:tt)*) => { $output.write_all( $statement.to_string().as_bytes() )?; $crate::beard_internal!($output, $($any)*); }; ($output:ident, if ( $condition:expr ) { $($statement:tt)+ } else { $($alternative:tt)+ } $($any:tt)*) => { if $condition { $crate::beard_internal!($output, $($statement)+); } else { $crate::beard_internal!($output, $($alternative)+); } $crate::beard_internal!($output, $($any)*); }; ($output:ident, if let $condition:pat = ( $value:expr ) { $($statement:tt)+ } $($any:tt)*) => { if let $condition = $value { $crate::beard_internal!($output, $($statement)+); } $crate::beard_internal!($output, $($any)*); }; ($output:ident, if ( $condition:expr ) { $($statement:tt)+ } $($any:tt)*) => { if $condition { $crate::beard_internal!($output, $($statement)+); } $crate::beard_internal!($output, $($any)*); }; ($output:ident, for $value:pat in ($into_iter:expr) { $($statement:tt)+ } $($any:tt)*) => { for $value in $into_iter.into_iter() { #![allow(clippy::into_iter_on_ref, array_into_iter)] $crate::beard_internal!($output, $($statement)+); } $crate::beard_internal!($output, $($any)*); }; } #[test] fn test() { use std::io::Write as _; const EXPECTED: &str = r##"Variables can be formatted as follow: value. Statement works too: 3 (so you can do special formatting if you want). as bytes directly: value The length of the stuff is not null value Optional value set 1 Optional value not set print thing: one print thing: two something custom"##; fn render() -> Result<String, std::io::Error> { let value = "value"; let stuff = ["one", "two"]; let optionals = [Some(1), None]; let mut output = Vec::new(); beard! { output, "Variables can be formatted as follow: " { value } ".\n" "Statement works too: " { 1 + 2} " (so you can do special formatting if you want).\n" if (value == "something") { "This test is not rendered" { value } } " as bytes directly: " [ { value.as_bytes() } ] "\n" if (!stuff.is_empty()) { "The length of the stuff is not null " { value } "\n" } else { "oops\n" } for optional in ( optionals ) { if let Some(value) = ( optional ) { "Optional value set " { value } "\n" } if let None = (optional) { "Optional value not set\n" } } for (_index, thing) in (stuff.iter().enumerate()) { "print thing: " { thing } "\n" } | | { output.write_all(b"something custom")?; } }; Ok(String::from_utf8(output).unwrap()) } let message = render().unwrap(); println!("{}", message); assert_eq!(EXPECTED, message); }