Thanks to visit codestin.com
Credit goes to github.com

Skip to content

BTreeMap requires Archived keys #585

@tv42

Description

@tv42

Hi. I'm trying to use BTreeMap and.. is it just me or does it seem like ArchivedBTreeMap is really hard to use? It's get method demands the archived key type, which is sometimes quite hard to construct.

Here's a simple case (key is u32) where it would have been nice to just use the unarchived key type, but making the archived flavor is easy enough:

use std::collections::BTreeMap;

#[derive(rkyv::Archive, rkyv::Serialize)]
struct Example {
    m: BTreeMap<u32, u32>,
}

fn main() {
    let value = Example { m: BTreeMap::new() };
    let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&value).unwrap();
    println!("{bytes:?}");

    let archived = rkyv::access::<ArchivedExample, rkyv::rancor::Error>(&bytes).unwrap();

    let want: u32 = 42;
    // PROBLEM: expected `&u32_le`, found `&u32`
    // let _found = archived.m.get(&want);

    let _found = archived.m.get(&rkyv::rend::u32_le::from_native(want));
}

However, it just gets harder and harder from there. Simply wrapping the u32 in a little struct makes constructing the ArchivedKey extremely inconvenient.
(Adding #[rkyv(compare(...)], or deriving just about anything that might be relevant, is of no help.)

use std::collections::BTreeMap;

#[derive(
    Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, rkyv::Archive, rkyv::Serialize, Debug,
)]
#[rkyv(derive(Ord, PartialOrd, Eq, PartialEq, Hash, Debug))]
#[rkyv(compare(PartialOrd, PartialEq))]
struct Key(u32);

#[derive(rkyv::Archive, rkyv::Serialize)]
struct Example {
    m: BTreeMap<Key, u32>,
}

fn main() {
    let value = Example {
        m: BTreeMap::from_iter([(Key(42), 13)]),
    };
    let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&value).unwrap();
    let archived = rkyv::access::<ArchivedExample, rkyv::rancor::Error>(&bytes).unwrap();

    let want: Key = Key(42);
    // PROBLEM: expected `&ArchivedKey`, found `&Key`
    // let _found = archived.m.get(&want);

    // iteration still works, and `k` here *is* an `&ArchivedKey`, but I wanted lookup
    for (k, v) in archived.m.iter() {
        if k == &want {
            println!("found {v}");
        }
    }
}

How am I supposed to call ArchivedBTreeMap::get?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions