Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deserialize a big fixed size array #573

Closed
Yamakaky opened this Issue Oct 6, 2016 · 3 comments

Comments

2 participants
@Yamakaky
Copy link

Yamakaky commented Oct 6, 2016

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.

@dtolnay

This comment has been minimized.

Copy link
Member

dtolnay commented Oct 6, 2016

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)
    }
}
@Yamakaky

This comment has been minimized.

Copy link
Author

Yamakaky commented Oct 6, 2016

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.

@dtolnay

This comment has been minimized.

Copy link
Member

dtolnay commented Oct 6, 2016

I filed serde-rs/serde-rs.github.io#23 to add this example to the website.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.