nostrdb-rs

nostrdb in rust!
git clone git://jb55.com/nostrdb-rs
Log | Files | Refs | Submodules | README | LICENSE

ndb_str.rs (1759B)


      1 use crate::{bindings, Note};
      2 
      3 pub struct NdbStr<'a> {
      4     ndb_str: bindings::ndb_str,
      5     note: Note<'a>,
      6 }
      7 
      8 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
      9 pub enum NdbStrVariant<'a> {
     10     Id(&'a [u8; 32]),
     11     Str(&'a str),
     12 }
     13 
     14 impl<'a> NdbStrVariant<'a> {
     15     pub fn id(&self) -> Option<&'a [u8; 32]> {
     16         match self {
     17             Self::Id(id) => Some(id),
     18             _ => None,
     19         }
     20     }
     21 
     22     pub fn str(&self) -> Option<&'a str> {
     23         match self {
     24             Self::Str(s) => Some(s),
     25             _ => None,
     26         }
     27     }
     28 }
     29 
     30 impl bindings::ndb_str {
     31     pub fn str(&self) -> *const ::std::os::raw::c_char {
     32         unsafe { self.__bindgen_anon_1.str_ }
     33     }
     34 
     35     pub fn id(&self) -> *const ::std::os::raw::c_uchar {
     36         unsafe { self.__bindgen_anon_1.id }
     37     }
     38 }
     39 
     40 impl<'a> NdbStr<'a> {
     41     pub fn note(&self) -> &Note<'a> {
     42         &self.note
     43     }
     44 
     45     pub(crate) fn new(ndb_str: bindings::ndb_str, note: Note<'a>) -> Self {
     46         NdbStr { ndb_str, note }
     47     }
     48 
     49     pub fn is_empty(&self) -> bool {
     50         self.len() == 0
     51     }
     52 
     53     pub fn len(&self) -> usize {
     54         if self.ndb_str.flag == (bindings::NDB_PACKED_ID as u8) {
     55             32
     56         } else {
     57             unsafe { libc::strlen(self.ndb_str.str()) }
     58         }
     59     }
     60 
     61     pub fn variant(&self) -> NdbStrVariant<'a> {
     62         if self.ndb_str.flag == (bindings::NDB_PACKED_ID as u8) {
     63             unsafe { NdbStrVariant::Id(&*(self.ndb_str.id() as *const [u8; 32])) }
     64         } else {
     65             let s = unsafe {
     66                 let byte_slice =
     67                     std::slice::from_raw_parts(self.ndb_str.str() as *const u8, self.len());
     68                 std::str::from_utf8_unchecked(byte_slice)
     69             };
     70 
     71             NdbStrVariant::Str(s)
     72         }
     73     }
     74 }