#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(not(feature = "alloc"))]
use crate::error::Error;
use crate::error::Result;
#[cfg(feature = "alloc")]
type Inner<K, V, const N: usize> = alloc::collections::BTreeMap<K, V>;
#[cfg(not(feature = "alloc"))]
type Inner<K, V, const N: usize> = heapless::LinearMap<K, V, N>;
#[allow(dead_code)]
pub struct BTreeMap<K, V, const N: usize>(Inner<K, V, N>);
impl<K, V, const N: usize> Clone for BTreeMap<K, V, N>
where
K: Clone + Eq,
V: Clone,
{
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<K, V, const N: usize> core::fmt::Debug for BTreeMap<K, V, N>
where
K: core::fmt::Debug + Eq,
V: core::fmt::Debug,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple("BTreeMap").field(&self.0).finish()
}
}
#[allow(dead_code)]
impl<K, V, const N: usize> BTreeMap<K, V, N>
where
K: Ord + Eq,
{
#[inline]
pub fn new() -> Self {
Self::default()
}
#[inline]
pub fn get(&self, key: &K) -> Option<&V> {
self.0.get(key)
}
#[inline]
pub fn contains_key(&self, key: &K) -> bool {
#[cfg(feature = "alloc")]
{
self.0.contains_key(key)
}
#[cfg(not(feature = "alloc"))]
{
self.0.get(key).is_some()
}
}
#[inline]
pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>> {
#[cfg(feature = "alloc")]
{
Ok(self.0.insert(key, value))
}
#[cfg(not(feature = "alloc"))]
{
self.0
.insert(key, value)
.map_err(|_| Error::Validation(crate::error::Error::MAX_NAME_SIZE_EXCEEDED))
}
}
#[inline]
pub fn remove(&mut self, key: &K) -> Option<V> {
self.0.remove(key)
}
}
#[allow(dead_code)]
impl<K, V, const N: usize> BTreeMap<K, V, N>
where
K: Eq,
{
#[inline]
pub fn len(&self) -> usize {
self.0.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[inline]
pub fn clear(&mut self) {
self.0.clear();
}
#[inline]
pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
self.0.iter()
}
#[inline]
pub fn keys(&self) -> impl Iterator<Item = &K> {
#[cfg(feature = "alloc")]
{
self.0.keys()
}
#[cfg(not(feature = "alloc"))]
{
self.0.iter().map(|(k, _)| k)
}
}
#[inline]
pub fn values(&self) -> impl Iterator<Item = &V> {
#[cfg(feature = "alloc")]
{
self.0.values()
}
#[cfg(not(feature = "alloc"))]
{
self.0.iter().map(|(_, v)| v)
}
}
}
impl<K, V, const N: usize> Default for BTreeMap<K, V, N>
where
K: Ord + Eq,
{
#[inline]
fn default() -> Self {
#[cfg(feature = "alloc")]
{
Self(Inner::new())
}
#[cfg(not(feature = "alloc"))]
{
Self(Inner::new())
}
}
}
impl<K, V, const N: usize> PartialEq for BTreeMap<K, V, N>
where
K: Ord + Eq,
V: PartialEq,
{
#[inline]
fn eq(&self, other: &Self) -> bool {
#[cfg(feature = "alloc")]
{
self.0 == other.0
}
#[cfg(not(feature = "alloc"))]
{
if self.len() != other.len() {
return false;
}
self.iter().all(|(k, v)| other.get(k) == Some(v))
}
}
}
impl<K, V, const N: usize> Eq for BTreeMap<K, V, N>
where
K: Ord + Eq,
V: Eq,
{
}