nostrdb-rs

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

ndb_str.rs (1383B)


      1 use crate::{bindings, Note};
      2 
      3 pub struct NdbStr<'a> {
      4     ndb_str: bindings::ndb_str,
      5     note: &'a 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 bindings::ndb_str {
     15     pub fn str(&self) -> *const ::std::os::raw::c_char {
     16         unsafe { self.__bindgen_anon_1.str_ }
     17     }
     18 
     19     pub fn id(&self) -> *const ::std::os::raw::c_uchar {
     20         unsafe { self.__bindgen_anon_1.id }
     21     }
     22 }
     23 
     24 impl<'a> NdbStr<'a> {
     25     pub fn note(&self) -> &'a Note<'a> {
     26         self.note
     27     }
     28 
     29     pub(crate) fn new(ndb_str: bindings::ndb_str, note: &'a Note<'a>) -> Self {
     30         NdbStr { ndb_str, note }
     31     }
     32 
     33     pub fn len(&self) -> usize {
     34         if self.ndb_str.flag == (bindings::NDB_PACKED_ID as u8) {
     35             32
     36         } else {
     37             unsafe { libc::strlen(self.ndb_str.str()) }
     38         }
     39     }
     40 
     41     pub fn variant(&self) -> NdbStrVariant<'a> {
     42         if self.ndb_str.flag == (bindings::NDB_PACKED_ID as u8) {
     43             unsafe { NdbStrVariant::Id(&*(self.ndb_str.id() as *const [u8; 32])) }
     44         } else {
     45             let s = unsafe {
     46                 let byte_slice =
     47                     std::slice::from_raw_parts(self.ndb_str.str() as *const u8, self.len());
     48                 std::str::from_utf8_unchecked(byte_slice)
     49             };
     50 
     51             NdbStrVariant::Str(s)
     52         }
     53     }
     54 }