Types convert problem

i have writed a test for u32 convert to &[u8] and &[u8] convert to u32.
like this:

pub struct ByteBuf {
        bytes: Vec<u8>,//bytes数据
        index: usize,//读写指针
    }
impl ByteBuf{
         pub fn push_u32(&mut self, i: u32) {
             unsafe {
                 let byte = transmute::<u32, [u8; 4]>(i);
                 for i in &byte {
                     self.bytes.push(*i);
                 }
             }
        }
        pub fn read_u32(&mut self) -> Result<u32,&str> {
               if self.bytes.len()-self.index<4{
                      return Err("NotEnough");
               }
               let b = &self.bytes[self.index..=self.index + 3];
               self.index += 4;
               let mut int = 0;
               unsafe {
                    let mut byte: [u8; 4] = [0; 4];

                    for i in 0..3 {
                      byte[i] = b[i];
                    }
                   int = transmute::<[u8; 4], u32>(byte);
             }
                Ok(int)
          }

}

i wanna call push_u32 fun,then call read_u32 for get the same number.
but when the number of i call push_u32 if the u32 value I passed in was too large, read_u32 got the wrong result.
for example:
then i call push_u32,and passed in a 1011000001,the bytes's values is[193,162,66,60],
it's not right values,if i call read_u32,i will get 4367041,not 1011000001.
if i call push_u32 10110001and passed in 10110001,the read_u32 will give me 10110001.
why? 1011000001 didn't spill over,but can not get right result.
pls help me.thanks

You don't need transmute. There are methods for this:

https://doc.rust-lang.org/std/primitive.u32.html#method.to_le_bytes

https://doc.rust-lang.org/std/primitive.u32.html#method.from_le_bytes

2 Likes

Like so

pub struct ByteBuf {
    bytes: Vec<u8>, //bytes数据
    index: usize,   //读写指针
}

impl ByteBuf {
    pub fn push_u32(&mut self, i: u32) {
        let bytes = i.to_ne_bytes();
        self.bytes.extend_from_slice(&bytes);
    }

    pub fn read_u32(&mut self) -> Option<u32> {
        let buf_bytes = self.bytes.get(self.index..self.index + 4)?;
        self.index += 4;
        
        let mut bytes = [0; 4];
        bytes.copy_from_slice(&buf_bytes);
        Some(u32::from_ne_bytes(bytes))
    }
}
1 Like

oh~,your code is work,thanks

thank u,i have see your url and understand

thank u,your code is work

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.