ciborium icon indicating copy to clipboard operation
ciborium copied to clipboard

[Bug]: Error in deserialization : Err(Semantic(None, "invalid type: bytes, expected array")) on array of u8

Open nicoxxl opened this issue 3 years ago • 3 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Code of Conduct

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

Current Behaviour

This code :

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct S {
    pubKey: [u8; 32] // or Vec<u8>, it produce the same error
}


fn main() {
    let data = vec![161, 102, 112, 117, 98, 75, 101, 121, 88, 32, 189, 182, 166, 93, 174, 37, 6, 247, 39, 203, 228, 101, 121, 197, 203, 42, 98, 138, 145, 12, 12, 76, 145, 168, 132, 185, 90, 18, 54, 28, 248, 170];
    let r = ciborium::de::from_reader::<S, _>(&data[..]);
    println!("{:?}", r);
}

Produce this error :

Err(Semantic(None, "invalid type: bytes, expected array"))

Expected Behaviour

Decoding bytes into a Vec<u8> or [u8; N] would be nice

Environment Information

Cargo.toml:

[package]
name = "z"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = { version = "1", features = ["derive"] }
ciborium = "0.2.0"

Steps To Reproduce

No response

nicoxxl avatar Aug 10 '22 14:08 nicoxxl

Also, this fails other way around. Serializing Vec<u8> results in an array. So, there is no obvious way to serialize Vec<u8> as ciborium::value::Value::Bytes.

lig avatar Aug 31 '22 17:08 lig

I've managed to solve the serialization issue with serde_bytes crate.

Adding #[serde(with = "serde_bytes")] (see example below) to a value declaration solves the issue for me.

pub struct MyStruct {
    #[serde(with = "serde_bytes")]
    pub data: Vec<u8>,
}

lig avatar Sep 05 '22 14:09 lig

@lig why is there a difference between Bytes and Vec<Value> where Value is an Integer ? In this case the Integer.rs is:

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Integer {
    number: N,
}
#[derive(Copy, Clone, Debug)]
enum N {
    U8(u8),
    U16(u16),
    U32(u32),
    U64(u64),

    I8(i8),
    I16(i16),
    I32(i32),
    I64(i64),
    I128(i128),

    USIZE(usize),
    ISIZE(isize),
}

I reimplement the integer.rs as an exemple: https://github.com/samuel-cavalcanti/ciborium/blob/main/ciborium/src/value/integer.rs

samuel-cavalcanti avatar Sep 20 '22 23:09 samuel-cavalcanti