Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

map/try_map for BoundedBTreeMap #11866

@benluelo

Description

@benluelo

It would be useful if there was a way to iterate over an &mut BoundedBTreeMap and mutate each key in place. This wouldn't affect the length of the map at all, so it would be safe. Perhaps a try_map or something similar would be good as well, to allow for short circuiting.

I would be happy to take this on if it's deemed useful.

(BoundedBTreeMap link for the lazy:

pub struct BoundedBTreeMap<K, V, S>(BTreeMap<K, V>, PhantomData<S>);
)

EDIT:

After some experimentation, I think this is a better API:

pub fn map<T>(self, mut f: impl FnMut((&K, V)) -> T) -> BoundedBTreeMap<K, T, S> {
    self.0
        .into_iter()
        .map(|(k, v)| {
            let t = f((&k, v));
            (k, t)
        })
        .try_collect()
        // SAFETY: No entries were added or removed.
        .unwrap()
}

pub fn try_map<T, E>(
    self,
    mut f: impl FnMut((&K, V)) -> Result<T, E>,
) -> Result<BoundedBTreeMap<K, T, S>, E> {
    Ok(self
        .0
        .into_iter()
        .map(|(k, v)| (f((&k, v)).map(|t| (k, t))))
        .collect::<Result<BTreeMap<_, _>, _>>()?
        .try_into()
        // SAFETY: No entries were added or removed.
        .unwrap())
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    J0-enhancementAn additional feature request.Z2-mediumCan be fixed by a coder with good Rust knowledge but little knowledge of the codebase.

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions