lib

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

encode.rs (1670B)


      1 use core::fmt;
      2 
      3 #[cfg(not(feature = "std"))]
      4 use alloc::{string::String, vec, vec::Vec};
      5 
      6 pub use crate::wire::{canonicalize_tags, empty_content};
      7 
      8 #[derive(Debug)]
      9 pub enum JobEncodeError {
     10     MissingProvidersForEncrypted,
     11     InvalidKind(u32),
     12     EmptyRequiredField(&'static str),
     13 }
     14 
     15 impl fmt::Display for JobEncodeError {
     16     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     17         match self {
     18             JobEncodeError::MissingProvidersForEncrypted => {
     19                 write!(f, "encrypted=true requires at least one provider ('p') tag")
     20             }
     21             JobEncodeError::InvalidKind(k) => write!(f, "invalid job event kind: {}", k),
     22             JobEncodeError::EmptyRequiredField(n) => write!(f, "empty required field: {}", n),
     23         }
     24     }
     25 }
     26 
     27 #[cfg(feature = "std")]
     28 impl std::error::Error for JobEncodeError {}
     29 
     30 #[cfg(feature = "json")]
     31 pub fn json_content<T: serde::Serialize>(value: &T) -> Result<String, JobEncodeError> {
     32     serde_json::to_string(value).map_err(|_| JobEncodeError::EmptyRequiredField("content-json"))
     33 }
     34 
     35 pub fn push_status_tag(tags: &mut Vec<Vec<String>>, status: &str, extra: Option<&str>) {
     36     let mut v = vec!["status".into(), status.into()];
     37     if let Some(e) = extra {
     38         v.push(e.into());
     39     }
     40     tags.push(v);
     41 }
     42 
     43 pub fn push_provider_tag(tags: &mut Vec<Vec<String>>, p: &str) {
     44     tags.push(vec!["p".into(), p.into()]);
     45 }
     46 
     47 pub fn push_relay_tag(tags: &mut Vec<Vec<String>>, r: &str) {
     48     tags.push(vec!["relays".into(), r.into()]);
     49 }
     50 
     51 pub fn assert_no_inputs_when_encrypted(tags: &[Vec<String>]) -> bool {
     52     !tags
     53         .iter()
     54         .any(|t| t.first().map(|s| s == "i").unwrap_or(false))
     55 }