use munge::munge;
use crate::{decode, encode, u64_le, Decode, Decoder, Encode, Encoder, Slot, WireEnvelope};
#[repr(C)]
pub struct RawWireUnion<'buf> {
ordinal: u64_le,
envelope: WireEnvelope<'buf>,
}
impl<'buf> RawWireUnion<'buf> {
pub fn encode_absent(slot: Slot<'_, Self>) {
munge!(let Self { mut ordinal, envelope } = slot);
*ordinal = u64_le::from_native(0);
WireEnvelope::encode_zero(envelope);
}
pub fn encode_as<E: Encoder + ?Sized, T: Encode<E>>(
value: &mut T,
ord: u64,
encoder: &mut E,
slot: Slot<'_, Self>,
) -> Result<(), encode::EncodeError> {
munge!(let Self { mut ordinal, envelope } = slot);
*ordinal = u64_le::from_native(ord);
WireEnvelope::encode_value(value, encoder, envelope)
}
pub fn encoded_ordinal(slot: Slot<'_, Self>) -> u64 {
munge!(let Self { ordinal, envelope: _ } = slot);
ordinal.to_native()
}
pub fn decode_absent(slot: Slot<'_, Self>) -> Result<(), decode::DecodeError> {
munge!(let Self { ordinal: _, envelope } = slot);
if !WireEnvelope::is_encoded_zero(envelope) {
return Err(decode::DecodeError::InvalidUnionEnvelope);
}
Ok(())
}
pub fn decode_unknown<D: Decoder<'buf> + ?Sized>(
slot: Slot<'_, Self>,
decoder: &mut D,
) -> Result<(), decode::DecodeError> {
munge!(let Self { ordinal: _, envelope } = slot);
WireEnvelope::decode_unknown(envelope, decoder)
}
pub fn decode_as<D: Decoder<'buf> + ?Sized, T: Decode<D>>(
slot: Slot<'_, Self>,
decoder: &mut D,
) -> Result<(), decode::DecodeError> {
munge!(let Self { ordinal: _, envelope } = slot);
WireEnvelope::decode_as::<D, T>(envelope, decoder)
}
pub fn null() -> Self {
Self { ordinal: u64_le::from_native(0), envelope: WireEnvelope::zero() }
}
pub fn is_some(&self) -> bool {
self.ordinal.to_native() != 0
}
pub fn is_none(&self) -> bool {
!self.is_some()
}
pub fn ordinal(&self) -> u64 {
self.ordinal.to_native()
}
pub fn get(&self) -> &WireEnvelope<'buf> {
&self.envelope
}
pub fn get_mut(&mut self) -> &mut WireEnvelope<'buf> {
&mut self.envelope
}
}