You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.5KB

  1. use std::collections::HashMap;
  2. use base64::{encode, decode};
  3. use pulldown_cmark as cmark;
  4. use tera::{Value, to_value, Result as TeraResult};
  5. pub fn markdown(value: Value, _: HashMap<String, Value>) -> TeraResult<Value> {
  6. let s = try_get_value!("markdown", "value", String, value);
  7. let mut html = String::new();
  8. let parser = cmark::Parser::new(&s);
  9. cmark::html::push_html(&mut html, parser);
  10. Ok(to_value(&html).unwrap())
  11. }
  12. pub fn base64_encode(value: Value, _: HashMap<String, Value>) -> TeraResult<Value> {
  13. let s = try_get_value!("base64_encode", "value", String, value);
  14. Ok(
  15. to_value(&encode(s.as_bytes())).unwrap()
  16. )
  17. }
  18. pub fn base64_decode(value: Value, _: HashMap<String, Value>) -> TeraResult<Value> {
  19. let s = try_get_value!("base64_decode", "value", String, value);
  20. Ok(
  21. to_value(
  22. &String::from_utf8(
  23. decode(s.as_bytes()).unwrap()
  24. ).unwrap()
  25. ).unwrap()
  26. )
  27. }
  28. #[cfg(test)]
  29. mod tests {
  30. use std::collections::HashMap;
  31. use tera::{to_value};
  32. use super::{markdown, base64_decode, base64_encode};
  33. #[test]
  34. fn markdown_filter() {
  35. let result = markdown(to_value(&"# Hey").unwrap(), HashMap::new());
  36. assert!(result.is_ok());
  37. assert_eq!(result.unwrap(), to_value(&"<h1>Hey</h1>\n").unwrap());
  38. }
  39. #[test]
  40. fn base64_encode_filter() {
  41. // from https://tools.ietf.org/html/rfc4648#section-10
  42. let tests = vec![
  43. ("", ""),
  44. ("f", "Zg=="),
  45. ("fo", "Zm8="),
  46. ("foo", "Zm9v"),
  47. ("foob", "Zm9vYg=="),
  48. ("fooba", "Zm9vYmE="),
  49. ("foobar", "Zm9vYmFy")
  50. ];
  51. for (input, expected) in tests {
  52. let args = HashMap::new();
  53. let result = base64_encode(to_value(input).unwrap(), args);
  54. assert!(result.is_ok());
  55. assert_eq!(result.unwrap(), to_value(expected).unwrap());
  56. }
  57. }
  58. #[test]
  59. fn base64_decode_filter() {
  60. let tests = vec![
  61. ("", ""),
  62. ("Zg==", "f"),
  63. ("Zm8=", "fo"),
  64. ("Zm9v", "foo"),
  65. ("Zm9vYg==", "foob"),
  66. ("Zm9vYmE=", "fooba"),
  67. ("Zm9vYmFy", "foobar")
  68. ];
  69. for (input, expected) in tests {
  70. let args = HashMap::new();
  71. let result = base64_decode(to_value(input).unwrap(), args);
  72. assert!(result.is_ok());
  73. assert_eq!(result.unwrap(), to_value(expected).unwrap());
  74. }
  75. }
  76. }