fidl_next/wire/string/
optional.rsuse core::fmt;
use core::str::from_utf8;
use munge::munge;
use crate::{
decode, encode, Decode, Decoder, Encoder, Slot, TakeFrom, WireOptionalVector, WireString,
WireVector,
};
#[derive(Default)]
#[repr(transparent)]
pub struct WireOptionalString<'buf> {
vec: WireOptionalVector<'buf, u8>,
}
impl<'buf> WireOptionalString<'buf> {
pub fn encode_present(slot: Slot<'_, Self>, len: u64) {
munge!(let Self { vec } = slot);
WireOptionalVector::encode_present(vec, len);
}
pub fn encode_absent(slot: Slot<'_, Self>) {
munge!(let Self { vec } = slot);
WireOptionalVector::encode_absent(vec);
}
pub fn is_some(&self) -> bool {
self.vec.is_some()
}
pub fn is_none(&self) -> bool {
self.vec.is_none()
}
pub fn take(&mut self) -> Option<WireString<'buf>> {
self.vec.take().map(|vec| unsafe { WireString::new_unchecked(vec) })
}
pub fn as_ref(&self) -> Option<&WireString<'buf>> {
self.vec.as_ref().map(|vec| unsafe { &*(vec as *const WireVector<'buf, u8>).cast() })
}
pub fn as_mut(&mut self) -> Option<&mut WireString<'buf>> {
self.vec.as_mut().map(|vec| unsafe { &mut *(vec as *mut WireVector<'buf, u8>).cast() })
}
}
impl fmt::Debug for WireOptionalString<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.as_ref().fmt(f)
}
}
unsafe impl<'buf, D: Decoder<'buf> + ?Sized> Decode<D> for WireOptionalString<'buf> {
fn decode(slot: Slot<'_, Self>, decoder: &mut D) -> Result<(), decode::DecodeError> {
munge!(let Self { mut vec } = slot);
WireOptionalVector::decode(vec.as_mut(), decoder)?;
let vec = unsafe { vec.deref_unchecked() };
if let Some(bytes) = vec.as_ref() {
from_utf8(bytes)?;
}
Ok(())
}
}
impl encode::EncodableOption for String {
type EncodedOption<'buf> = WireOptionalString<'buf>;
}
impl<E: Encoder + ?Sized> encode::EncodeOption<E> for String {
fn encode_option(
this: Option<&mut Self>,
encoder: &mut E,
slot: Slot<'_, Self::EncodedOption<'_>>,
) -> Result<(), encode::EncodeError> {
if let Some(string) = this {
encoder.write(string.as_bytes());
WireOptionalString::encode_present(slot, string.len() as u64);
} else {
WireOptionalString::encode_absent(slot);
}
Ok(())
}
}
impl TakeFrom<WireOptionalString<'_>> for Option<String> {
fn take_from(from: &mut WireOptionalString<'_>) -> Self {
from.as_mut().map(String::take_from)
}
}