Serde: Deserialize a big fixed size array

Created on 6 Oct 2016  路  3Comments  路  Source: serde-rs/serde

struct Screen([Pixel; SCREEN_SIZE]). I would like to implement Deserialize on this type. How could I do this? I may not be a good idea to do 10000+ variables like for in https://github.com/serde-rs/serde/blob/master/serde/src/de/impls.rs#L557-L647.

support

Most helpful comment

Cool, thanks! Maybe you should put it somewhere, it could be useful for someone else.
I hope we soon have type level integers, life sucks without it.

All 3 comments

Lack of type level integers limits what we can provide out of the box when it comes to arrays. The standard library does the same thing for Default, Debug, Eq, PartialEq, Ord, PartialOrd, AsRef, AsMut, Borrow, BorrowMut, Clone, Hash, IntoIterator - they are implemented for [T; 0] through [T; 32] only.

Here is one way to handle struct Screen([Pixel; SCREEN_SIZE]) specifically:

use serde::{Deserialize, Deserializer};
use serde::de::{self, Visitor, SeqVisitor};

impl Deserialize for Screen {
    fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
        where D: Deserializer
    {
        struct ScreenVisitor;

        impl Visitor for ScreenVisitor {
            type Value = Screen;

            fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Screen, V::Error>
                where V: SeqVisitor
            {
                let mut screen = Screen([0; SCREEN_SIZE]);

                for i in 0..SCREEN_SIZE {
                    screen.0[i] = match try!(visitor.visit()) {
                        Some(val) => val,
                        None => { return Err(de::Error::end_of_stream()); }
                    };
                }

                try!(visitor.end());

                Ok(screen)
            }
        }

        deserializer.deserialize_seq_fixed_size(SCREEN_SIZE, ScreenVisitor)
    }
}

Cool, thanks! Maybe you should put it somewhere, it could be useful for someone else.
I hope we soon have type level integers, life sucks without it.

I filed https://github.com/serde-rs/serde-rs.github.io/issues/23 to add this example to the website.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dtolnay picture dtolnay  路  4Comments

dtolnay picture dtolnay  路  3Comments

dtolnay picture dtolnay  路  3Comments

dtolnay picture dtolnay  路  3Comments

pitkley picture pitkley  路  3Comments