hirschenberger / modbus-rs

Modbus implementation in pure Rust
MIT License
89 stars 22 forks source link

byteorder big, wordorder little #35

Closed hce closed 1 year ago

hce commented 1 year ago

I am porting some code from python to rust. In python I write:

    decoder = BinaryPayloadDecoder.fromRegisters(
            r.registers, byteorder=Endian.Big, wordorder=Endian.Little)

In rust, I write: let buf = binary::unpack_bytes(&registers);

The problem is, that even when specifying the "word order" here, it wouldn't work, because it needs to be applied on a per register basis. So currently, I read 8 and 16 bit values directly from the buffer, while I hacked this helper function for 32 bit values:

    fn read_big_little_i32<R: Read>(mut inbuf: R) -> Result<i32> {
        let a = inbuf.read_u8()?;
        let b = inbuf.read_u8()?;
        let c = inbuf.read_u8()?;
        let d = inbuf.read_u8()?;
        let buf = &[c, d, a, b];
        (&buf[..]).read_i32::<byteorder::BE>()
    }

Am I missing something here? Can this be done simpler? :-)

hirschenberger commented 1 year ago

How about:

fn read_big_little_i32<R: Read>(mut inbuf: R) -> Result<i32> {
   let n = inbuf.read_i32::<BigEndian>()?;
   Ok( n << 16 | n >> 16)
}

Should be pretty efficient.