Skip to content

Commit

Permalink
ZeroMap: Conversion functions for AsULE keys and values
Browse files Browse the repository at this point in the history
  • Loading branch information
sffc committed Oct 20, 2023
1 parent 61469c9 commit cc54276
Showing 1 changed file with 79 additions and 1 deletion.
80 changes: 79 additions & 1 deletion utils/zerovec/src/map/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use super::*;
use crate::ule::{AsULE, EncodeAsVarULE, VarULE};
use crate::{VarZeroVec, ZeroSlice, ZeroVec};
use crate::{VarZeroVec, ZeroSlice, ZeroVec, ZeroVecError};
use alloc::borrow::Borrow;
use alloc::boxed::Box;
use core::cmp::Ordering;
Expand Down Expand Up @@ -321,6 +321,84 @@ where
}
}

impl<'a, K, V> ZeroMap<'a, K, V>
where
K: ZeroMapKV<'a, Container = ZeroVec<'a, K>> + ?Sized,
V: ZeroMapKV<'a> + ?Sized,
K: AsULE,
{
/// Cast a `ZeroMap<K, V>` to `ZeroMap<P, V>` where `K` and `P` are [`AsULE`] types
/// with the same representation.
///
/// If `K` and `P` have different ordering semantics, unexpected behavior may occur.
pub fn cast_zv_k<P>(self) -> ZeroMap<'a, P, V>
where
P: AsULE<ULE = K::ULE> + ZeroMapKV<'a, Container = ZeroVec<'a, P>> + ?Sized,
{
ZeroMap {
keys: self.keys.cast(),
values: self.values,
}
}

/// Convert a `ZeroMap<K, V>` to `ZeroMap<P, V>` where `K` and `P` are [`AsULE`] types
/// with the same size.
///
/// If `K` and `P` have different ordering semantics, unexpected behavior may occur.
///
/// # Panics
///
/// Panics if `K::ULE` and `P::ULE` are not the same size.
pub fn try_convert_zv_k<P>(self) -> Result<ZeroMap<'a, P, V>, ZeroVecError>
where
P: AsULE + ZeroMapKV<'a, Container = ZeroVec<'a, P>> + ?Sized,
{
Ok(ZeroMap {
keys: self.keys.try_into_converted()?,
values: self.values,
})
}
}

impl<'a, K, V> ZeroMap<'a, K, V>
where
K: ZeroMapKV<'a> + ?Sized,
V: ZeroMapKV<'a, Container = ZeroVec<'a, V>> + ?Sized,
V: AsULE,
{
/// Cast a `ZeroMap<K, V>` to `ZeroMap<K, P>` where `V` and `P` are [`AsULE`] types
/// with the same representation.
///
/// If `V` and `P` have different ordering semantics, unexpected behavior may occur.
pub fn cast_zv_v<P>(self) -> ZeroMap<'a, K, P>
where
P: AsULE<ULE = V::ULE> + ZeroMapKV<'a, Container = ZeroVec<'a, P>> + ?Sized,
{
ZeroMap {
keys: self.keys,
values: self.values.cast(),
}
}

/// Convert a `ZeroMap<K, V>` to `ZeroMap<K, P>` where `V` and `P` are [`AsULE`] types
/// with the same size.
///
/// If `V` and `P` have different ordering semantics, unexpected behavior may occur.
///
/// # Panics
///
/// Panics if `V::ULE` and `P::ULE` are not the same size.
pub fn try_convert_zv_v<P>(self) -> Result<ZeroMap<'a, K, P>, ZeroVecError>
where
P: AsULE + ZeroMapKV<'a, Container = ZeroVec<'a, P>> + ?Sized,
{
Ok(ZeroMap {
keys: self.keys,
values: self.values.try_into_converted()?,
})
}
}

impl<'a, K, V> ZeroMap<'a, K, V>
where
K: ZeroMapKV<'a> + ?Sized + Ord,
Expand Down

0 comments on commit cc54276

Please sign in to comment.