struct DcdWriter<'a>(&'a mut [u8]);
impl<'a> DcdWriter<'a> {
fn write_len<T: num_traits::ToPrimitive>(
&'a mut self,
value: T,
len: usize,
) -> &'a mut DcdWriter<'a> {
dcd_encode(value.to_u32().unwrap(), &mut self.0[0..len]);
self.0 = &mut self.0[len..];
self
}
fn write_var<T: num_traits::ToPrimitive>(&'a mut self, value: &T) -> &'a mut DcdWriter<'a> {
let len = std::mem::size_of_val(&value);
self.write_len((*value).to_u32().unwrap(), len)
}
fn write_simple<'b: 'a>(&'b mut self, value: u32, len: usize) {
dcd_encode(value, &mut self.0[0..len]);
self.0 = &mut self.0[len..];
}
}
impl BeQueryData {
pub fn to_packet(&self, packet: &mut PckStruct) {
packet.p_param.resize(48, 0x00);
let mut writer = DcdWriter(&mut packet.p_param);
writer
.write_len(self.status_flags, 6)
.write_var(&self.vcharge_max_pos)
.write_var(&self.vcharge_max_neg)
.write_len(self.icharge_max_pos, 3)
.write_len(self.icharge_max_neg, 3)
.write_var(&self.vbat_pos)
.write_var(&self.vbat_neg)
.write_len(self.ibat_pos, 5)
.write_len(self.ibat_neg, 5)
.write_var(&self.aut_time)
.write_var(&self.soc)
.write_var(&self.soh)
.write_var(&self.tbd);
// this does not compile
writer.write_simple(self.status_flags, 6);
writer.write_simple(self.vcharge_max_pos as u32, 6);
}
}
Why the code above gives an error for the last two lines (‘cannot borrow writer
as mutable more than once at a time’)?
I understand that it is related to the lifetime ‘b but why writer is still considered borrowed after the call has to write_simple is returned?
And why the calls to the other methods does not represent any problem?
Finally is there a way to eliminate the build error on write_simple?