hpl_toolkit/utils/
short_vec.rsuse anchor_lang::prelude::*;
#[cfg(feature = "compression")]
use crate::compression::*;
#[cfg(feature = "schema")]
use crate::schema::*;
#[cfg_attr(feature = "debug", derive(Debug))]
#[derive(Clone, Eq, PartialEq)]
pub struct ShortVec<T: Clone + AnchorSerialize + AnchorDeserialize>(Vec<T>);
impl<T: Clone + AnchorSerialize + AnchorDeserialize> ShortVec<T> {
pub fn new(vec: Vec<T>) -> std::io::Result<Self> {
if vec.len() > 255 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Short string length shall not exceed 255",
));
}
Ok(Self(vec))
}
pub fn new_unchecked(vec: Vec<T>) -> Self {
Self::new(vec).expect("Short Vec length shall not exceed 255")
}
pub unsafe fn new_unsafe(vec: Vec<T>) -> Self {
Self::new_unchecked(vec)
}
pub fn to_vec(&self) -> Vec<T> {
self.0.clone()
}
pub fn into_vec(self) -> Vec<T> {
self.0
}
}
impl<T: Clone + AnchorSerialize + AnchorDeserialize> Into<Vec<T>> for ShortVec<T> {
fn into(self) -> Vec<T> {
self.0
}
}
impl<T: Clone + AnchorSerialize + AnchorDeserialize> From<Vec<T>> for ShortVec<T> {
fn from(value: Vec<T>) -> Self {
Self::new_unchecked(value)
}
}
impl<T: Clone + AnchorSerialize + AnchorDeserialize> From<&Vec<T>> for ShortVec<T> {
fn from(value: &Vec<T>) -> Self {
Self::new_unchecked(value.to_vec())
}
}
impl<T: Clone + AnchorSerialize + AnchorDeserialize + PartialEq> PartialEq<Vec<T>> for ShortVec<T> {
fn eq(&self, other: &Vec<T>) -> bool {
self.0 == *other
}
}
impl<T: AnchorSerialize + AnchorDeserialize + Clone> AnchorSerialize for ShortVec<T> {
fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
let length = self.0.len() as u8;
length.serialize(writer)?;
self.0.iter().try_for_each(|item| item.serialize(writer))?;
Ok(())
}
}
impl<T: AnchorSerialize + AnchorDeserialize + Clone> AnchorDeserialize for ShortVec<T> {
fn deserialize_reader<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
let mut buf: [u8; 1] = [0; 1];
let limit = reader.read(&mut buf)?;
if limit != 1 {
#[cfg(feature = "log")]
crate::logger::debug!("limit: {}, Buf: {:?}", limit, buf);
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Unexpected length of input",
));
}
let mut vec = Vec::<T>::new();
for _ in 0..buf[0] {
vec.push(T::deserialize_reader(reader)?);
}
Ok(Self(vec))
}
}
#[cfg(feature = "idl-build")]
impl<T: AnchorSerialize + AnchorDeserialize + Clone> anchor_lang::IdlBuild for ShortVec<T> {
fn __anchor_private_full_path() -> String {
format!("{0}::{1}", "hpl_toolkit::utils::short_vec", "ShortVec",)
}
}
#[cfg(feature = "compression")]
impl<T: Clone + AnchorSerialize + AnchorDeserialize + ToNode> ToNode for ShortVec<T> {
fn to_node(&self) -> [u8; 32] {
self.0.to_node()
}
}
#[cfg(feature = "schema")]
impl<T: Clone + AnchorSerialize + AnchorDeserialize + ToNode + ToSchema> ToSchema for ShortVec<T> {
fn schema() -> Schema {
Vec::<T>::schema()
}
fn schema_value(&self) -> SchemaValue {
self.0.schema_value()
}
}