lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README | LICENSE

encode.rs (2240B)


      1 #[cfg(not(feature = "std"))]
      2 use alloc::{string::ToString, vec::Vec};
      3 
      4 use radroots_events::{
      5     article::RadrootsArticle,
      6     kinds::KIND_ARTICLE,
      7     tags::{TAG_D, TAG_IMAGE, TAG_PUBLISHED_AT, TAG_SUMMARY, TAG_T, TAG_TITLE},
      8 };
      9 
     10 use crate::d_tag::validate_d_tag;
     11 use crate::error::EventEncodeError;
     12 use crate::field_helpers::{push_optional_tag, push_tag, validate_non_empty_field};
     13 use crate::social_helpers::push_location_tags;
     14 use crate::wire::WireEventParts;
     15 
     16 const DEFAULT_KIND: u32 = KIND_ARTICLE;
     17 
     18 pub fn article_build_tags(article: &RadrootsArticle) -> Result<Vec<Vec<String>>, EventEncodeError> {
     19     validate_article(article)?;
     20     let mut tags = Vec::new();
     21     push_tag(&mut tags, TAG_D, article.d_tag.as_str());
     22     push_tag(&mut tags, TAG_TITLE, article.title.as_str());
     23     push_optional_tag(&mut tags, TAG_SUMMARY, article.summary.as_deref());
     24     push_optional_tag(&mut tags, TAG_IMAGE, article.image.as_deref());
     25     if let Some(published_at) = article.published_at {
     26         push_tag(&mut tags, TAG_PUBLISHED_AT, published_at.to_string());
     27     }
     28     if let Some(farm) = article.farm.as_ref() {
     29         crate::social_helpers::push_farm_anchor(&mut tags, farm);
     30     }
     31     if let Some(location) = article.location.as_ref() {
     32         push_location_tags(&mut tags, location);
     33     }
     34     if let Some(topics) = article.topics.as_ref() {
     35         for topic in topics {
     36             push_optional_tag(&mut tags, TAG_T, Some(topic.as_str()));
     37         }
     38     }
     39     Ok(tags)
     40 }
     41 
     42 pub fn to_wire_parts(article: &RadrootsArticle) -> Result<WireEventParts, EventEncodeError> {
     43     to_wire_parts_with_kind(article, DEFAULT_KIND)
     44 }
     45 
     46 pub fn to_wire_parts_with_kind(
     47     article: &RadrootsArticle,
     48     kind: u32,
     49 ) -> Result<WireEventParts, EventEncodeError> {
     50     if kind != DEFAULT_KIND {
     51         return Err(EventEncodeError::InvalidKind(kind));
     52     }
     53     Ok(WireEventParts {
     54         kind,
     55         content: article.content.clone(),
     56         tags: article_build_tags(article)?,
     57     })
     58 }
     59 
     60 fn validate_article(article: &RadrootsArticle) -> Result<(), EventEncodeError> {
     61     validate_d_tag(&article.d_tag, "d_tag")?;
     62     validate_non_empty_field(&article.title, "title")?;
     63     validate_non_empty_field(&article.content, "content")?;
     64     Ok(())
     65 }