use alloc::{boxed::Box, vec::Vec};

use crate::{des::Deserializer, ser::Serializer, Deserialize, Serialize};

impl<T: Serialize> Serialize for Vec<T> {
    fn serialize<S: Serializer>(&self, serializer: &mut S) -> Result<(), S::Error> {
        serializer.write_usize(self.len())?;
        for item in self.iter() {
            item.serialize(serializer)?;
        }
        Ok(())
    }
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Vec<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: &mut D) -> Result<Self, D::Error> {
        let len = deserializer.read_usize()?;
        let mut result = Vec::new();
        for _ in 0..len {
            let item = T::deserialize(deserializer)?;
            result.push(item);
        }
        Ok(result)
    }
}

impl Serialize for Box<str> {
    fn serialize<S: Serializer>(&self, serializer: &mut S) -> Result<(), S::Error> {
        serializer.write_str(self)
    }
}
impl<'de> Deserialize<'de> for Box<str> {
    fn deserialize<D: Deserializer<'de>>(deserializer: &mut D) -> Result<Self, D::Error> {
        deserializer.read_str().map(Into::into)
    }
}
