use core::borrow::Borrow;
use litemap::LiteMap;
use super::Key;
use super::Value;
#[derive(Clone, PartialEq, Eq, Debug, Default, Hash, PartialOrd, Ord)]
pub struct Fields(Inner);
#[cfg(feature = "alloc")]
type Inner = LiteMap<Key, Value>;
#[cfg(not(feature = "alloc"))]
type Inner = LiteMap<Key, Value, &'static [(Key, Value)]>;
impl Fields {
#[inline]
pub const fn new() -> Self {
Self(LiteMap::new())
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn clear(&mut self) -> Self {
core::mem::take(self)
}
pub fn contains_key<Q>(&self, key: &Q) -> bool
where
Key: Borrow<Q>,
Q: Ord,
{
self.0.contains_key(key)
}
pub fn get<Q>(&self, key: &Q) -> Option<&Value>
where
Key: Borrow<Q>,
Q: Ord,
{
self.0.get(key)
}
#[cfg(feature = "alloc")]
pub fn set(&mut self, key: Key, value: Value) -> Option<Value> {
self.0.insert(key, value)
}
#[cfg(feature = "alloc")]
pub fn retain_by_key<F>(&mut self, mut predicate: F)
where
F: FnMut(&Key) -> bool,
{
self.0.retain(|k, _| predicate(k))
}
pub(crate) fn for_each_subtag_str<E, F>(&self, f: &mut F) -> Result<(), E>
where
F: FnMut(&str) -> Result<(), E>,
{
for (k, v) in self.0.iter() {
f(k.as_str())?;
v.for_each_subtag_str(f)?;
}
Ok(())
}
#[cfg(test)]
pub(crate) fn from_tuple_vec(v: Vec<(Key, Value)>) -> Self {
v.into_iter().collect()
}
}
#[cfg(feature = "alloc")]
impl From<LiteMap<Key, Value>> for Fields {
fn from(map: LiteMap<Key, Value>) -> Self {
Self(map)
}
}
#[cfg(feature = "alloc")]
impl FromIterator<(Key, Value)> for Fields {
fn from_iter<I: IntoIterator<Item = (Key, Value)>>(iter: I) -> Self {
LiteMap::from_iter(iter).into()
}
}
impl_writeable_for_key_value!(Fields, "h0", "hybrid", "m0", "m0-true");