jt_util 0.1.1

jt808 jt1078等基础库实现
Documentation
use std::{fmt, usize};

use bytes::{BufMut, Bytes, BytesMut};
use encoding::{all::GBK, DecoderTrap, EncoderTrap, Encoding};

use serde::{de::Visitor, Deserialize, Serialize};
#[derive(Debug, Default, Clone)]
pub struct BytesGBK {
    bytes: Bytes,
}

struct BytesGBKVisitor;

impl<'de> Visitor<'de> for BytesGBKVisitor {
    type Value = BytesGBK;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("expecting")
    }
    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        let mut b = BytesGBK::default();
        b.set_val(v);
        Ok(b)
    }
}
impl<'de> Deserialize<'de> for BytesGBK {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = deserializer.deserialize_str(BytesGBKVisitor {})?;
        Ok(s)
    }
}
impl Serialize for BytesGBK {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.get_val().serialize(serializer)
    }
}
impl BytesGBK {
    pub fn new() -> Self {
        BytesGBK {
            bytes: Bytes::new(),
        }
    }
    pub fn new_with_bytes(bytes: Bytes) -> Self {
        BytesGBK { bytes }
    }
    pub fn bytes_len(&self) -> usize {
        self.bytes.len()
    }
    fn trim0(&mut self) -> usize {
        if self.bytes_len() > 0 {
            match self.bytes.iter().position(|b| *b > 0) {
                Some(i) => {
                    if i > 0 {
                        let _ = self.bytes.split_to(i);
                    }
                }
                None => self.bytes.clear(),
            }
        }
        if self.bytes_len() > 0 {
            match self.bytes.iter().rev().position(|b| *b > 0) {
                Some(i) => {
                    if i > 0 {
                        self.bytes.truncate(self.bytes_len() - i);
                    }
                }
                None => self.bytes.clear(),
            }
        }
        self.bytes_len()
    }
    pub fn set_bytes_len(&mut self, fixed_len: usize, add_start_0: bool) {
        let mut len = self.bytes.len();
        if fixed_len > 0 && len != fixed_len {
            len = self.trim0();
            if len > fixed_len {
                self.bytes.split_at(fixed_len);
            } else if len < fixed_len {
                let mut buf = BytesMut::with_capacity(fixed_len);

                if add_start_0 {
                    while buf.len() + len < fixed_len {
                        buf.put_u8(0u8);
                    }
                }
                buf.put(self.bytes.clone());

                while buf.len() < fixed_len {
                    buf.put_u8(0u8);
                }
                self.bytes = buf.freeze();
            }
        }
    }
    pub fn get_fixed_bytes(&mut self, fixed_len: usize, add_start_0: bool) -> Bytes {
        self.set_bytes_len(fixed_len, add_start_0);
        self.get_bytes()
    }
    pub fn get_bytes(&self) -> Bytes {
        self.bytes.clone()
    }
    pub fn set_bytes(&mut self, bytes: Bytes) {
        self.bytes = bytes;
    }
    pub fn get_val(&self) -> String {
        match GBK.decode(self.bytes.as_ref(), DecoderTrap::Ignore) {
            Ok(val) => val.trim_matches(|p| p == '\0').to_string(),
            Err(_) => String::default(),
        }
    }
    pub fn set_val(&mut self, val: &str) {
        match GBK.encode(val, EncoderTrap::Ignore) {
            Ok(b) => {
                self.bytes = Bytes::from(b);
            }
            Err(_) => {
                self.bytes.clear();
            }
        }
    }
}

impl fmt::Display for BytesGBK {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.get_val())
    }
}
// impl fmt::Debug for BytesGBK{
//     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//         f.debug_struct("BytesGBK").field("bytes", &self.bytes).field("value", &self.get_val()).finish()
//     }
// }