Skip to content

[Bug]: Decoding a flattened map type with integer key type fails with an "invalid type" error #153

@regexident

Description

@regexident

Is there an existing issue for this?

  • I have searched the existing issues

Code of Conduct

  • I agree to follow this project's Code of Conduct

Current Behaviour

Decoding a map with integer key type …

#[serde(flatten)]
inner: HashMap<u8, _>

… returns an error:

Semantic(None, "invalid type: integer `42`, expected str or bytes")

Expected Behaviour

I'd expect it to be able to decode the field just fine?

Environment Information

n/a

Steps To Reproduce

The following code works fine:

[package]
name = "ciborium-repro"
version = "0.1.0"
edition = "2024"

[dependencies]
ciborium = "0.2.2"
serde = { version = "1.0.219", features = ["derive"] }
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Dummy {
    inner: HashMap<u8, String>,
}

fn main() {
    let before: Dummy = {
        let mut inner = HashMap::default();
        inner.insert(42, "bar".to_owned());
        Dummy { inner }
    };
    println!("before: {before:?}");

    let mut buf = vec![];
    ciborium::into_writer(&before, &mut buf).unwrap();

    println!("encoded: {buf:?}");

    let after: Dummy = ciborium::from_reader(buf.as_slice()).unwrap();
    println!("after: {after:?}");
}
before: Dummy { inner: {42: "bar"} }
encoded: [161, 101, 105, 110, 110, 101, 114, 161, 24, 42, 99, 98, 97, 114]
after: Dummy { inner: {42: "bar"} }

But add #[serde(flatten)] on Dummy's inner field and you get this:

#[derive(Debug, Serialize, Deserialize)]
struct Dummy {
    #[serde(flatten)]
    inner: HashMap<u8, String>,
}
before: Dummy { inner: {42: "bar"} }
encoded: [191, 24, 42, 99, 98, 97, 114, 255]

thread 'main' panicked at src/main.rs:24:62:
called `Result::unwrap()` on an `Err` value: Semantic(None, "invalid type: integer `42`, expected str or bytes")

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    Status

    New

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions