Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Mapping for Map Types

IDL map types are mapped to BTreeMap from the Rust standard library. A BTreeMap is used rather than HashMap because it provides deterministic ordering, which is important for serialization consistency.

// IDL
typedef map<string, int32> StringToInt;
typedef map<int32, sequence<string>> IntToStrings;
#![allow(unused)]
fn main() {
// Rust
pub type StringToInt = ::std::collections::BTreeMap<String, i32>;
pub type IntToStrings = ::std::collections::BTreeMap<i32, Vec<String>>;
}

Default Value

The default value for a map is an empty map:

#![allow(unused)]
fn main() {
::std::collections::BTreeMap::new()
}

Bounded Maps

IDL allows specifying a maximum size for maps. This bound is not enforced at the type level in Rust, but is checked during serialization. An implementation may choose to provide a custom BoundedMap<K, V, N> type for such purposes.

// IDL
typedef map<string, int32, 100> BoundedMap;
#![allow(unused)]
fn main() {
// Rust - bound is not reflected in the type
pub type BoundedMap = ::std::collections::BTreeMap<String, i32>;
}

Key Type Requirements

Map keys must be types that implement Ord in Rust (required by BTreeMap). This means the key type must have total order. Floating-point types (f32, f64) cannot be used as map keys because they do not implement Ord.

Constant Maps

Map constants are initialized using the BTreeMap::from constructor with an array of key-value tuples:

// IDL
const map<string, int32> MY_MAP = {
    {"one", 1},
    {"two", 2},
    {"three", 3}
};
#![allow(unused)]
fn main() {
// Rust
pub static MY_MAP: ::std::sync::LazyLock<::std::collections::BTreeMap<String, i32>> =
    ::std::sync::LazyLock::new(|| {
        ::std::collections::BTreeMap::from([
            ("one".into(), 1),
            ("two".into(), 2),
            ("three".into(), 3),
        ])
    });
}

Note that map constants containing non-trivial types (like String keys) use LazyLock for lazy initialization. See Constants for details.