use munge::munge;
use crate::decoder::InternalHandleDecoder;
use crate::{decode, encode, u64_le, Decode, Decoder, Encode, Encoder, Slot, WireEnvelope};
#[repr(C)]
pub struct RawWireUnion {
ordinal: u64_le,
envelope: WireEnvelope,
}
impl RawWireUnion {
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_static<D: InternalHandleDecoder + ?Sized>(
slot: Slot<'_, Self>,
decoder: &mut D,
) -> Result<(), decode::DecodeError> {
munge!(let Self { ordinal: _, envelope } = slot);
WireEnvelope::decode_unknown_static(envelope, decoder)
}
pub fn decode_unknown<'buf, 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_static<D: InternalHandleDecoder + ?Sized, T: Decode<D>>(
slot: Slot<'_, Self>,
decoder: &mut D,
) -> Result<(), decode::DecodeError> {
munge!(let Self { ordinal: _, envelope } = slot);
WireEnvelope::decode_as_static::<D, T>(envelope, decoder)
}
pub fn decode_as<'buf, 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 {
&self.envelope
}
pub fn get_mut(&mut self) -> &mut WireEnvelope {
&mut self.envelope
}
pub unsafe fn clone_unchecked<T: Clone>(&self) -> Self {
Self { ordinal: self.ordinal, envelope: unsafe { self.envelope.clone_unchecked::<T>() } }
}
}