<commit_before>use std::fmt::Show;
use test::Bencher;

use serialize::{Decoder, Decodable};

use de::{Deserializer, Deserializable};

//////////////////////////////////////////////////////////////////////////////

#[deriving(Show)]
enum Error {
    EndOfStream,
    SyntaxError,
}

//////////////////////////////////////////////////////////////////////////////

mod decoder {
    use std::vec;
    use serialize;

    use super::{Error, EndOfStream, SyntaxError};

    pub struct Decoder {
        len: uint,
        iter: vec::MoveItems<int>,
    }

    impl Decoder {
        #[inline]
        pub fn new(values: Vec<int>) -> Decoder {
            Decoder {
                len: values.len(),
                iter: values.move_iter(),
            }
        }
    }

    impl serialize::Decoder<Error> for Decoder {
        // Primitive types:
        fn read_nil(&mut self) -> Result<(), Error> { Err(SyntaxError) }
        fn read_uint(&mut self) -> Result<uint, Error> { Err(SyntaxError) }
        fn read_u64(&mut self) -> Result<u64, Error> { Err(SyntaxError) }
        fn read_u32(&mut self) -> Result<u32, Error> { Err(SyntaxError) }
        fn read_u16(&mut self) -> Result<u16, Error> { Err(SyntaxError) }
        fn read_u8(&mut self) -> Result<u8, Error> { Err(SyntaxError) }
        #[inline]
        fn read_int(&mut self) -> Result<int, Error> {
            match self.iter.next() {
                Some(value) => Ok(value),
                None => Err(EndOfStream),
            }
        }
        fn read_i64(&mut self) -> Result<i64, Error> { Err(SyntaxError) }
        fn read_i32(&mut self) -> Result<i32, Error> { Err(SyntaxError) }
        fn read_i16(&mut self) -> Result<i16, Error> { Err(SyntaxError) }
        fn read_i8(&mut self) -> Result<i8, Error> { Err(SyntaxError) }
        fn read_bool(&mut self) -> Result<bool, Error> { Err(SyntaxError) }
        fn read_f64(&mut self) -> Result<f64, Error> { Err(SyntaxError) }
        fn read_f32(&mut self) -> Result<f32, Error> { Err(SyntaxError) }
        fn read_char(&mut self) -> Result<char, Error> { Err(SyntaxError) }
        fn read_str(&mut self) -> Result<StrBuf, Error> { Err(SyntaxError) }

        // Compound types:
        fn read_enum<T>(&mut self, _name: &str, _f: |&mut Decoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }

        fn read_enum_variant<T>(&mut self,
                                _names: &[&str],
                                _f: |&mut Decoder, uint| -> Result<T, Error>)
                                -> Result<T, Error> { Err(SyntaxError) }
        fn read_enum_variant_arg<T>(&mut self,
                                    _a_idx: uint,
                                    _f: |&mut Decoder| -> Result<T, Error>)
                                    -> Result<T, Error> { Err(SyntaxError) }

        fn read_enum_struct_variant<T>(&mut self,
                                       _names: &[&str],
                                       _f: |&mut Decoder, uint| -> Result<T, Error>)
                                       -> Result<T, Error> { Err(SyntaxError) }
        fn read_enum_struct_variant_field<T>(&mut self,
                                             _f_name: &str,
                                             _f_idx: uint,
                                             _f: |&mut Decoder| -> Result<T, Error>)
                                             -> Result<T, Error> { Err(SyntaxError) }

        fn read_struct<T>(&mut self, _s_name: &str, _len: uint, _f: |&mut Decoder| -> Result<T, Error>)
                          -> Result<T, Error> { Err(SyntaxError) }
        fn read_struct_field<T>(&mut self,
                                _f_name: &str,
                                _f_idx: uint,
                                _f: |&mut Decoder| -> Result<T, Error>)
                                -> Result<T, Error> { Err(SyntaxError) }

        fn read_tuple<T>(&mut self, _f: |&mut Decoder, uint| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
        fn read_tuple_arg<T>(&mut self, _a_idx: uint, _f: |&mut Decoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }

        fn read_tuple_struct<T>(&mut self,
                                _s_name: &str,
                                _f: |&mut Decoder, uint| -> Result<T, Error>)
                                -> Result<T, Error> { Err(SyntaxError) }
        fn read_tuple_struct_arg<T>(&mut self,
                                    _a_idx: uint,
                                    _f: |&mut Decoder| -> Result<T, Error>)
                                    -> Result<T, Error> { Err(SyntaxError) }

        // Specialized types:
        fn read_option<T>(&mut self, _f: |&mut Decoder, bool| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }

        #[inline]
        fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> Result<T, Error>) -> Result<T, Error> {
            f(self, self.len)
        }
        #[inline]
        fn read_seq_elt<T>(&mut self, _idx: uint, f: |&mut Decoder| -> Result<T, Error>) -> Result<T, Error> {
            f(self)
        }

        fn read_map<T>(&mut self, _f: |&mut Decoder, uint| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
        fn read_map_elt_key<T>(&mut self, _idx: uint, _f: |&mut Decoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
        fn read_map_elt_val<T>(&mut self, _idx: uint, _f: |&mut Decoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
    }
}

//////////////////////////////////////////////////////////////////////////////

mod deserializer {
    //use std::num;
    use std::vec;

    use super::{Error, EndOfStream, SyntaxError};

    use de;

    #[deriving(Eq, Show)]
    enum State {
        StartState,
        SepOrEndState,
        EndState,
    }

    pub struct Deserializer {
        state: State,
        len: uint,
        iter: vec::MoveItems<int>,
    }

    impl Deserializer {
        #[inline]
        pub fn new(values: Vec<int>) -> Deserializer {
            Deserializer {
                state: StartState,
                len: values.len(),
                iter: values.move_iter(),
            }
        }
    }

    impl Iterator<Result<de::Token, Error>> for Deserializer {
        #[inline]
        fn next(&mut self) -> Option<Result<de::Token, Error>> {
            match self.state {
                StartState => {
                    self.state = SepOrEndState;
                    Some(Ok(de::SeqStart(self.len)))
                }
                SepOrEndState => {
                    match self.iter.next() {
                        Some(value) => {
                            Some(Ok(de::Int(value)))
                        }
                        None => {
                            self.state = EndState;
                            Some(Ok(de::End))
                        }
                    }
                }
                EndState => {
                    None
                }
            }
        }
    }

    impl de::Deserializer<Error> for Deserializer {
        #[inline]
        fn end_of_stream_error(&self) -> Error {
            EndOfStream
        }

        #[inline]
        fn syntax_error(&self) -> Error {
            SyntaxError
        }
    }
}

//////////////////////////////////////////////////////////////////////////////

fn run_decoder<
    E: Show,
    D: Decoder<E>,
    T: Clone + Eq + Show + Decodable<D, E>
>(mut d: D, value: T) {
    let v: T = Decodable::decode(&mut d).unwrap();

    assert_eq!(value, v);
}

fn run_deserializer<
    E: Show,
    D: Deserializer<E>,
    T: Clone + Eq + Show + Deserializable<E, D>
>(mut d: D, value: T) {
    let v: T = Deserializable::deserialize(&mut d).unwrap();

    assert_eq!(value, v);
}

#[bench]
fn bench_decoder_vec_int_000(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = vec!();
        run_decoder(decoder::Decoder::new(v.clone()), v)
    })
}

#[bench]
fn bench_deserializer_vec_int_000(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = vec!();
        run_deserializer(deserializer::Deserializer::new(v.clone()), v)
    })
}

#[bench]
fn bench_decoder_vec_int_003(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = vec!(1, 2, 3);
        run_decoder(decoder::Decoder::new(v.clone()), v)
    })
}

#[bench]
fn bench_deserializer_vec_int_003(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = vec!(1, 2, 3);
        run_deserializer(deserializer::Deserializer::new(v.clone()), v)
    })
}

#[bench]
fn bench_decoder_vec_int_100(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = range(0, 100).collect();
        run_decoder(decoder::Decoder::new(v.clone()), v)
    })
}

#[bench]
fn bench_deserializer_vec_int_100(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = range(0, 100).collect();
        run_deserializer(deserializer::Deserializer::new(v.clone()), v)
    })
}
<commit_msg>Add Vec<u8> benchmarks<commit_after>use std::fmt::Show;
use test::Bencher;

use serialize::{Decoder, Decodable};

use de::{Deserializer, Deserializable};

//////////////////////////////////////////////////////////////////////////////

#[deriving(Show)]
enum Error {
    EndOfStream,
    SyntaxError,
}

//////////////////////////////////////////////////////////////////////////////

mod decoder {
    use std::vec;
    use serialize;

    use super::{Error, EndOfStream, SyntaxError};

    pub struct IntDecoder {
        len: uint,
        iter: vec::MoveItems<int>,
    }

    impl IntDecoder {
        #[inline]
        pub fn new(values: Vec<int>) -> IntDecoder {
            IntDecoder {
                len: values.len(),
                iter: values.move_iter(),
            }
        }
    }

    impl serialize::Decoder<Error> for IntDecoder {
        // Primitive types:
        fn read_nil(&mut self) -> Result<(), Error> { Err(SyntaxError) }
        fn read_uint(&mut self) -> Result<uint, Error> { Err(SyntaxError) }
        fn read_u64(&mut self) -> Result<u64, Error> { Err(SyntaxError) }
        fn read_u32(&mut self) -> Result<u32, Error> { Err(SyntaxError) }
        fn read_u16(&mut self) -> Result<u16, Error> { Err(SyntaxError) }
        fn read_u8(&mut self) -> Result<u8, Error> { Err(SyntaxError) }
        #[inline]
        fn read_int(&mut self) -> Result<int, Error> {
            match self.iter.next() {
                Some(value) => Ok(value),
                None => Err(EndOfStream),
            }
        }
        fn read_i64(&mut self) -> Result<i64, Error> { Err(SyntaxError) }
        fn read_i32(&mut self) -> Result<i32, Error> { Err(SyntaxError) }
        fn read_i16(&mut self) -> Result<i16, Error> { Err(SyntaxError) }
        fn read_i8(&mut self) -> Result<i8, Error> { Err(SyntaxError) }
        fn read_bool(&mut self) -> Result<bool, Error> { Err(SyntaxError) }
        fn read_f64(&mut self) -> Result<f64, Error> { Err(SyntaxError) }
        fn read_f32(&mut self) -> Result<f32, Error> { Err(SyntaxError) }
        fn read_char(&mut self) -> Result<char, Error> { Err(SyntaxError) }
        fn read_str(&mut self) -> Result<StrBuf, Error> { Err(SyntaxError) }

        // Compound types:
        fn read_enum<T>(&mut self, _name: &str, _f: |&mut IntDecoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }

        fn read_enum_variant<T>(&mut self,
                                _names: &[&str],
                                _f: |&mut IntDecoder, uint| -> Result<T, Error>)
                                -> Result<T, Error> { Err(SyntaxError) }
        fn read_enum_variant_arg<T>(&mut self,
                                    _a_idx: uint,
                                    _f: |&mut IntDecoder| -> Result<T, Error>)
                                    -> Result<T, Error> { Err(SyntaxError) }

        fn read_enum_struct_variant<T>(&mut self,
                                       _names: &[&str],
                                       _f: |&mut IntDecoder, uint| -> Result<T, Error>)
                                       -> Result<T, Error> { Err(SyntaxError) }
        fn read_enum_struct_variant_field<T>(&mut self,
                                             _f_name: &str,
                                             _f_idx: uint,
                                             _f: |&mut IntDecoder| -> Result<T, Error>)
                                             -> Result<T, Error> { Err(SyntaxError) }

        fn read_struct<T>(&mut self, _s_name: &str, _len: uint, _f: |&mut IntDecoder| -> Result<T, Error>)
                          -> Result<T, Error> { Err(SyntaxError) }
        fn read_struct_field<T>(&mut self,
                                _f_name: &str,
                                _f_idx: uint,
                                _f: |&mut IntDecoder| -> Result<T, Error>)
                                -> Result<T, Error> { Err(SyntaxError) }

        fn read_tuple<T>(&mut self, _f: |&mut IntDecoder, uint| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
        fn read_tuple_arg<T>(&mut self, _a_idx: uint, _f: |&mut IntDecoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }

        fn read_tuple_struct<T>(&mut self,
                                _s_name: &str,
                                _f: |&mut IntDecoder, uint| -> Result<T, Error>)
                                -> Result<T, Error> { Err(SyntaxError) }
        fn read_tuple_struct_arg<T>(&mut self,
                                    _a_idx: uint,
                                    _f: |&mut IntDecoder| -> Result<T, Error>)
                                    -> Result<T, Error> { Err(SyntaxError) }

        // Specialized types:
        fn read_option<T>(&mut self, _f: |&mut IntDecoder, bool| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }

        #[inline]
        fn read_seq<T>(&mut self, f: |&mut IntDecoder, uint| -> Result<T, Error>) -> Result<T, Error> {
            f(self, self.len)
        }
        #[inline]
        fn read_seq_elt<T>(&mut self, _idx: uint, f: |&mut IntDecoder| -> Result<T, Error>) -> Result<T, Error> {
            f(self)
        }

        fn read_map<T>(&mut self, _f: |&mut IntDecoder, uint| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
        fn read_map_elt_key<T>(&mut self, _idx: uint, _f: |&mut IntDecoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
        fn read_map_elt_val<T>(&mut self, _idx: uint, _f: |&mut IntDecoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
    }

    pub struct U8Decoder {
        len: uint,
        iter: vec::MoveItems<u8>,
    }

    impl U8Decoder {
        #[inline]
        pub fn new(values: Vec<u8>) -> U8Decoder {
            U8Decoder {
                len: values.len(),
                iter: values.move_iter(),
            }
        }
    }

    impl serialize::Decoder<Error> for U8Decoder {
        // Primitive types:
        fn read_nil(&mut self) -> Result<(), Error> { Err(SyntaxError) }
        fn read_uint(&mut self) -> Result<uint, Error> { Err(SyntaxError) }
        fn read_u64(&mut self) -> Result<u64, Error> { Err(SyntaxError) }
        fn read_u32(&mut self) -> Result<u32, Error> { Err(SyntaxError) }
        fn read_u16(&mut self) -> Result<u16, Error> { Err(SyntaxError) }
        #[inline]
        fn read_u8(&mut self) -> Result<u8, Error> {
            match self.iter.next() {
                Some(value) => Ok(value),
                None => Err(EndOfStream),
            }
        }
        #[inline]
        fn read_int(&mut self) -> Result<int, Error> { Err(SyntaxError) }
        fn read_i64(&mut self) -> Result<i64, Error> { Err(SyntaxError) }
        fn read_i32(&mut self) -> Result<i32, Error> { Err(SyntaxError) }
        fn read_i16(&mut self) -> Result<i16, Error> { Err(SyntaxError) }
        fn read_i8(&mut self) -> Result<i8, Error> { Err(SyntaxError) }
        fn read_bool(&mut self) -> Result<bool, Error> { Err(SyntaxError) }
        fn read_f64(&mut self) -> Result<f64, Error> { Err(SyntaxError) }
        fn read_f32(&mut self) -> Result<f32, Error> { Err(SyntaxError) }
        fn read_char(&mut self) -> Result<char, Error> { Err(SyntaxError) }
        fn read_str(&mut self) -> Result<StrBuf, Error> { Err(SyntaxError) }

        // Compound types:
        fn read_enum<T>(&mut self, _name: &str, _f: |&mut U8Decoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }

        fn read_enum_variant<T>(&mut self,
                                _names: &[&str],
                                _f: |&mut U8Decoder, uint| -> Result<T, Error>)
                                -> Result<T, Error> { Err(SyntaxError) }
        fn read_enum_variant_arg<T>(&mut self,
                                    _a_idx: uint,
                                    _f: |&mut U8Decoder| -> Result<T, Error>)
                                    -> Result<T, Error> { Err(SyntaxError) }

        fn read_enum_struct_variant<T>(&mut self,
                                       _names: &[&str],
                                       _f: |&mut U8Decoder, uint| -> Result<T, Error>)
                                       -> Result<T, Error> { Err(SyntaxError) }
        fn read_enum_struct_variant_field<T>(&mut self,
                                             _f_name: &str,
                                             _f_idx: uint,
                                             _f: |&mut U8Decoder| -> Result<T, Error>)
                                             -> Result<T, Error> { Err(SyntaxError) }

        fn read_struct<T>(&mut self, _s_name: &str, _len: uint, _f: |&mut U8Decoder| -> Result<T, Error>)
                          -> Result<T, Error> { Err(SyntaxError) }
        fn read_struct_field<T>(&mut self,
                                _f_name: &str,
                                _f_idx: uint,
                                _f: |&mut U8Decoder| -> Result<T, Error>)
                                -> Result<T, Error> { Err(SyntaxError) }

        fn read_tuple<T>(&mut self, _f: |&mut U8Decoder, uint| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
        fn read_tuple_arg<T>(&mut self, _a_idx: uint, _f: |&mut U8Decoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }

        fn read_tuple_struct<T>(&mut self,
                                _s_name: &str,
                                _f: |&mut U8Decoder, uint| -> Result<T, Error>)
                                -> Result<T, Error> { Err(SyntaxError) }
        fn read_tuple_struct_arg<T>(&mut self,
                                    _a_idx: uint,
                                    _f: |&mut U8Decoder| -> Result<T, Error>)
                                    -> Result<T, Error> { Err(SyntaxError) }

        // Specialized types:
        fn read_option<T>(&mut self, _f: |&mut U8Decoder, bool| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }

        #[inline]
        fn read_seq<T>(&mut self, f: |&mut U8Decoder, uint| -> Result<T, Error>) -> Result<T, Error> {
            f(self, self.len)
        }
        #[inline]
        fn read_seq_elt<T>(&mut self, _idx: uint, f: |&mut U8Decoder| -> Result<T, Error>) -> Result<T, Error> {
            f(self)
        }

        fn read_map<T>(&mut self, _f: |&mut U8Decoder, uint| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
        fn read_map_elt_key<T>(&mut self, _idx: uint, _f: |&mut U8Decoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
        fn read_map_elt_val<T>(&mut self, _idx: uint, _f: |&mut U8Decoder| -> Result<T, Error>) -> Result<T, Error> { Err(SyntaxError) }
    }
}

//////////////////////////////////////////////////////////////////////////////

mod deserializer {
    //use std::num;
    use std::vec;

    use super::{Error, EndOfStream, SyntaxError};

    use de;

    #[deriving(Eq, Show)]
    enum State {
        StartState,
        SepOrEndState,
        EndState,
    }

    pub struct IntDeserializer {
        state: State,
        len: uint,
        iter: vec::MoveItems<int>,
    }

    impl IntDeserializer {
        #[inline]
        pub fn new(values: Vec<int>) -> IntDeserializer {
            IntDeserializer {
                state: StartState,
                len: values.len(),
                iter: values.move_iter(),
            }
        }
    }

    impl Iterator<Result<de::Token, Error>> for IntDeserializer {
        #[inline]
        fn next(&mut self) -> Option<Result<de::Token, Error>> {
            match self.state {
                StartState => {
                    self.state = SepOrEndState;
                    Some(Ok(de::SeqStart(self.len)))
                }
                SepOrEndState => {
                    match self.iter.next() {
                        Some(value) => {
                            Some(Ok(de::Int(value)))
                        }
                        None => {
                            self.state = EndState;
                            Some(Ok(de::End))
                        }
                    }
                }
                EndState => {
                    None
                }
            }
        }
    }

    impl de::Deserializer<Error> for IntDeserializer {
        #[inline]
        fn end_of_stream_error(&self) -> Error {
            EndOfStream
        }

        #[inline]
        fn syntax_error(&self) -> Error {
            SyntaxError
        }
    }

    pub struct U8Deserializer {
        state: State,
        len: uint,
        iter: vec::MoveItems<u8>,
    }

    impl U8Deserializer {
        #[inline]
        pub fn new(values: Vec<u8>) -> U8Deserializer {
            U8Deserializer {
                state: StartState,
                len: values.len(),
                iter: values.move_iter(),
            }
        }
    }

    impl Iterator<Result<de::Token, Error>> for U8Deserializer {
        #[inline]
        fn next(&mut self) -> Option<Result<de::Token, Error>> {
            match self.state {
                StartState => {
                    self.state = SepOrEndState;
                    Some(Ok(de::SeqStart(self.len)))
                }
                SepOrEndState => {
                    match self.iter.next() {
                        Some(value) => {
                            Some(Ok(de::U8(value)))
                        }
                        None => {
                            self.state = EndState;
                            Some(Ok(de::End))
                        }
                    }
                }
                EndState => {
                    None
                }
            }
        }
    }

    impl de::Deserializer<Error> for U8Deserializer {
        #[inline]
        fn end_of_stream_error(&self) -> Error {
            EndOfStream
        }

        #[inline]
        fn syntax_error(&self) -> Error {
            SyntaxError
        }
    }
}

//////////////////////////////////////////////////////////////////////////////

fn run_decoder<
    E: Show,
    D: Decoder<E>,
    T: Clone + Eq + Show + Decodable<D, E>
>(mut d: D, value: T) {
    let v: T = Decodable::decode(&mut d).unwrap();

    assert_eq!(value, v);
}

fn run_deserializer<
    E: Show,
    D: Deserializer<E>,
    T: Clone + Eq + Show + Deserializable<E, D>
>(mut d: D, value: T) {
    let v: T = Deserializable::deserialize(&mut d).unwrap();

    assert_eq!(value, v);
}

#[bench]
fn bench_decoder_vec_int_000(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = vec!();
        run_decoder(decoder::IntDecoder::new(v.clone()), v)
    })
}

#[bench]
fn bench_deserializer_vec_int_000(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = vec!();
        run_deserializer(deserializer::IntDeserializer::new(v.clone()), v)
    })
}

#[bench]
fn bench_decoder_vec_int_003(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = vec!(1, 2, 3);
        run_decoder(decoder::IntDecoder::new(v.clone()), v)
    })
}

#[bench]
fn bench_deserializer_vec_int_003(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = vec!(1, 2, 3);
        run_deserializer(deserializer::IntDeserializer::new(v.clone()), v)
    })
}

#[bench]
fn bench_decoder_vec_int_100(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = range(0, 100).collect();
        run_decoder(decoder::IntDecoder::new(v.clone()), v)
    })
}

#[bench]
fn bench_deserializer_vec_int_100(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<int> = range(0, 100).collect();
        run_deserializer(deserializer::IntDeserializer::new(v.clone()), v)
    })
}

#[bench]
fn bench_decoder_vec_u8_000(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<u8> = vec!();
        run_decoder(decoder::U8Decoder::new(v.clone()), v)
    })
}

#[bench]
fn bench_deserializer_vec_u8_000(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<u8> = vec!();
        run_deserializer(deserializer::U8Deserializer::new(v.clone()), v)
    })
}

#[bench]
fn bench_decoder_vec_u8_003(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<u8> = vec!(1, 2, 3);
        run_decoder(decoder::U8Decoder::new(v.clone()), v)
    })
}

#[bench]
fn bench_deserializer_vec_u8_003(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<u8> = vec!(1, 2, 3);
        run_deserializer(deserializer::U8Deserializer::new(v.clone()), v)
    })
}

#[bench]
fn bench_decoder_vec_u8_100(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<u8> = range(0u8, 100).collect();
        run_decoder(decoder::U8Decoder::new(v.clone()), v)
    })
}

#[bench]
fn bench_deserializer_vec_u8_100(b: &mut Bencher) {
    b.iter(|| {
        let v: Vec<u8> = range(0u8, 100).collect();
        run_deserializer(deserializer::U8Deserializer::new(v.clone()), v)
    })
}
<|endoftext|>


<commit_before>use nalgebra::{Vector2, Dot};
use std::cmp::max;
use super::rounding_error_tolerant_math::*;

use std::io::Write;
macro_rules! printlnerr(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

// TODO: polymorphic in number of dimensions, and numeric type
// TODO: optimize away the pointless inefficiencies I introduced
// note: the third time is not acceleration, but the coefficient of X squared, which is 2 times acceleration
pub type Coordinate = i64;
#[derive (Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
pub struct QuadraticTrajectory {
  data: [[Coordinate; 3]; 2],
  time_scale_shift: u32,
  max_distance_traveled_at_once: i64,
}

fn distance_squared_would_be(first: (Coordinate, &QuadraticTrajectory),
                             second: (Coordinate, &QuadraticTrajectory),
                             when: Coordinate)
                             -> Option<Coordinate> {
  if let Some(third) = first.1.updated_by(when - first.0) {
    if let Some(more) = second.1.updated_by(when - second.0) {
      let displacement = third.evaluate() - more.evaluate();
      return Some(displacement.dot(&displacement));
    }
  }
  None
}

impl QuadraticTrajectory {
  pub fn new(time_scale_shift: u32,
             max_distance_traveled_at_once: i64,
             coordinates: [Coordinate; 6])
             -> QuadraticTrajectory {
    QuadraticTrajectory {
      time_scale_shift: time_scale_shift,
      max_distance_traveled_at_once: max_distance_traveled_at_once,
      data: [[coordinates[0], coordinates[2], coordinates[4]],
             [coordinates[1], coordinates[3], coordinates[5]]],
    }
  }

  pub fn updated_by(&self, time: Coordinate) -> Option<QuadraticTrajectory> {
    let mut result = self.clone();
    for quadratic in result.data.iter_mut() {
      if !quadratic_move_origin_rounding_change_towards_0(quadratic.as_mut(),
                                                              time,
                                                              self.time_scale_shift,max_error_for_distance_traveled (self.max_distance_traveled_at_once)) {return None;}
    }
    Some(result)
  }

  pub fn update_by(&mut self, time: Coordinate) {
    for quadratic in self.data.iter_mut() {
      assert!(quadratic_move_origin_rounding_change_towards_0(quadratic.as_mut(),
                                                              time,
                                                              self.time_scale_shift,max_error_for_distance_traveled (self.max_distance_traveled_at_once)));
    }
  }

  pub fn add_acceleration(&mut self, acceleration: Vector2<Coordinate>) {
    self.data[0][2] += acceleration[0] * 2;
    self.data[1][2] += acceleration[1] * 2;
  }
  pub fn add_velocity(&mut self, velocity: Vector2<Coordinate>) {
    self.data[0][2] += velocity[0];
    self.data[1][2] += velocity[1];
  }
  pub fn evaluate(&self) -> Vector2<Coordinate> {
    Vector2::new(self.data[0][0], self.data[1][0])

  }

  // Bounds are min and max for the first dimension, then min and max for the second dimension
  pub fn approximately_when_escapes(&self,
                                    base: Coordinate,
                                    now: Coordinate,
                                    bounds: [[Coordinate; 2]; 2])
                                    -> Option<Coordinate> {
    time_until_which_quadratic_trajectory_may_remain_in_bounds (now - base, & self.data, & bounds, self.time_scale_shift, max_error_for_distance_traveled (self.max_distance_traveled_at_once)).map (| time | time + base)
  }

  // direction == -1->"when the distance between the trajectories drops below the distance argument"
  // direction == 1->"when the distance between the trajectories exceeds the distance argument"
  pub fn approximately_when_distance_passes(distance: Coordinate,
                                            direction: Coordinate,
                                            first: (Coordinate, &QuadraticTrajectory),
                                            second: (Coordinate, &QuadraticTrajectory))
                                            -> Option<Coordinate> {
    assert!(first.1.time_scale_shift == second.1.time_scale_shift,
            "we don't actually support interactions between trajectories with different scales");
    assert!(first.1.max_distance_traveled_at_once == second.1.max_distance_traveled_at_once,
            "we don't actually support interactions between trajectories with different error \
             limits");

    let base = max(first.0, second.0);
    if (distance_squared_would_be(first, second, base)
      .expect("we shouldn't have already maxed out our distance traveled at the \
               BEGINNING of the test!") - distance * distance) * direction > 0 {
      printlnerr!("rejefoo");
      return Some(base);
    }

    let intervals =
      quadratic_trajectories_possible_distance_crossing_intervals(distance,
                                                                  (first.0,
                                                                   &[first.1.data[0],
                                                                     first.1.data[1]]),
                                                                  (second.0,
                                                                   &[second.1.data[0],
                                                                     second.1.data[1]]),
                                                                  first.1.time_scale_shift,max_error_for_distance_traveled (first.1.max_distance_traveled_at_once));
    for interval in intervals.iter() {
      if interval.max() != i64::max_value() && interval.max() + 1 > base {
        if let Some(future_distance_squared) = distance_squared_would_be(first,
                                                                         second,
                                                                         interval.max() + 1) {
          if (future_distance_squared - distance * distance) * direction > 0 {
            return Some(interval.max() + 1);
          } //else {printlnerr!("rejected interval for not ending in the correct position")}
        }
      } //else {printlnerr!("rejected interval for being in the past")}
    }
    None
  }
}
<commit_msg>Fixed changing acceleration instead of velocity<commit_after>use nalgebra::{Vector2, Dot};
use std::cmp::max;
use super::rounding_error_tolerant_math::*;

use std::io::Write;
macro_rules! printlnerr(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

// TODO: polymorphic in number of dimensions, and numeric type
// TODO: optimize away the pointless inefficiencies I introduced
// note: the third time is not acceleration, but the coefficient of X squared, which is 2 times acceleration
pub type Coordinate = i64;
#[derive (Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
pub struct QuadraticTrajectory {
  data: [[Coordinate; 3]; 2],
  time_scale_shift: u32,
  max_distance_traveled_at_once: i64,
}

fn distance_squared_would_be(first: (Coordinate, &QuadraticTrajectory),
                             second: (Coordinate, &QuadraticTrajectory),
                             when: Coordinate)
                             -> Option<Coordinate> {
  if let Some(third) = first.1.updated_by(when - first.0) {
    if let Some(more) = second.1.updated_by(when - second.0) {
      let displacement = third.evaluate() - more.evaluate();
      return Some(displacement.dot(&displacement));
    }
  }
  None
}

impl QuadraticTrajectory {
  pub fn new(time_scale_shift: u32,
             max_distance_traveled_at_once: i64,
             coordinates: [Coordinate; 6])
             -> QuadraticTrajectory {
    QuadraticTrajectory {
      time_scale_shift: time_scale_shift,
      max_distance_traveled_at_once: max_distance_traveled_at_once,
      data: [[coordinates[0], coordinates[2], coordinates[4]],
             [coordinates[1], coordinates[3], coordinates[5]]],
    }
  }

  pub fn updated_by(&self, time: Coordinate) -> Option<QuadraticTrajectory> {
    let mut result = self.clone();
    for quadratic in result.data.iter_mut() {
      if !quadratic_move_origin_rounding_change_towards_0(quadratic.as_mut(),
                                                              time,
                                                              self.time_scale_shift,max_error_for_distance_traveled (self.max_distance_traveled_at_once)) {return None;}
    }
    Some(result)
  }

  pub fn update_by(&mut self, time: Coordinate) {
    for quadratic in self.data.iter_mut() {
      assert!(quadratic_move_origin_rounding_change_towards_0(quadratic.as_mut(),
                                                              time,
                                                              self.time_scale_shift,max_error_for_distance_traveled (self.max_distance_traveled_at_once)));
    }
  }

  pub fn add_acceleration(&mut self, acceleration: Vector2<Coordinate>) {
    self.data[0][2] += acceleration[0] * 2;
    self.data[1][2] += acceleration[1] * 2;
  }
  pub fn add_velocity(&mut self, velocity: Vector2<Coordinate>) {
    self.data[0][1] += velocity[0];
    self.data[1][1] += velocity[1];
  }
  pub fn evaluate(&self) -> Vector2<Coordinate> {
    Vector2::new(self.data[0][0], self.data[1][0])

  }

  // Bounds are min and max for the first dimension, then min and max for the second dimension
  pub fn approximately_when_escapes(&self,
                                    base: Coordinate,
                                    now: Coordinate,
                                    bounds: [[Coordinate; 2]; 2])
                                    -> Option<Coordinate> {
    time_until_which_quadratic_trajectory_may_remain_in_bounds (now - base, & self.data, & bounds, self.time_scale_shift, max_error_for_distance_traveled (self.max_distance_traveled_at_once)).map (| time | time + base)
  }

  // direction == -1->"when the distance between the trajectories drops below the distance argument"
  // direction == 1->"when the distance between the trajectories exceeds the distance argument"
  pub fn approximately_when_distance_passes(distance: Coordinate,
                                            direction: Coordinate,
                                            first: (Coordinate, &QuadraticTrajectory),
                                            second: (Coordinate, &QuadraticTrajectory))
                                            -> Option<Coordinate> {
    assert!(first.1.time_scale_shift == second.1.time_scale_shift,
            "we don't actually support interactions between trajectories with different scales");
    assert!(first.1.max_distance_traveled_at_once == second.1.max_distance_traveled_at_once,
            "we don't actually support interactions between trajectories with different error \
             limits");

    let base = max(first.0, second.0);
    if (distance_squared_would_be(first, second, base)
      .expect("we shouldn't have already maxed out our distance traveled at the \
               BEGINNING of the test!") - distance * distance) * direction > 0 {
      printlnerr!("rejefoo");
      return Some(base);
    }

    let intervals =
      quadratic_trajectories_possible_distance_crossing_intervals(distance,
                                                                  (first.0,
                                                                   &[first.1.data[0],
                                                                     first.1.data[1]]),
                                                                  (second.0,
                                                                   &[second.1.data[0],
                                                                     second.1.data[1]]),
                                                                  first.1.time_scale_shift,max_error_for_distance_traveled (first.1.max_distance_traveled_at_once));
    for interval in intervals.iter() {
      if interval.max() != i64::max_value() && interval.max() + 1 > base {
        if let Some(future_distance_squared) = distance_squared_would_be(first,
                                                                         second,
                                                                         interval.max() + 1) {
          if (future_distance_squared - distance * distance) * direction > 0 {
            return Some(interval.max() + 1);
          } //else {printlnerr!("rejected interval for not ending in the correct position")}
        }
      } //else {printlnerr!("rejected interval for being in the past")}
    }
    None
  }
}
<|endoftext|>


<commit_before>use super::encode::Metadata;
use crate::core::dependency::DepKind;
use crate::core::{Dependency, PackageId, PackageIdSpec, Summary, Target};
use crate::util::errors::CargoResult;
use crate::util::interning::InternedString;
use crate::util::Graph;
use std::borrow::Borrow;
use std::collections::{HashMap, HashSet};
use std::fmt;

/// Represents a fully-resolved package dependency graph. Each node in the graph
/// is a package and edges represent dependencies between packages.
///
/// Each instance of `Resolve` also understands the full set of features used
/// for each package.
pub struct Resolve {
    /// A graph, whose vertices are packages and edges are dependency specifications
    /// from `Cargo.toml`. We need a `HashSet` here because the same package
    /// might be present in both `[dependencies]` and `[build-dependencies]`.
    graph: Graph<PackageId, HashSet<Dependency>>,
    /// Replacements from the `[replace]` table.
    replacements: HashMap<PackageId, PackageId>,
    /// Inverted version of `replacements`.
    reverse_replacements: HashMap<PackageId, PackageId>,
    /// Features enabled for a given package.
    features: HashMap<PackageId, Vec<InternedString>>,
    /// Checksum for each package. A SHA256 hash of the `.crate` file used to
    /// validate the correct crate file is used. This is `None` for sources
    /// that do not use `.crate` files, like path or git dependencies.
    checksums: HashMap<PackageId, Option<String>>,
    /// "Unknown" metadata. This is a collection of extra, unrecognized data
    /// found in the `[metadata]` section of `Cargo.lock`, preserved for
    /// forwards compatibility.
    metadata: Metadata,
    /// `[patch]` entries that did not match anything, preserved in
    /// `Cargo.lock` as the `[[patch.unused]]` table array. Tracking unused
    /// patches helps prevent Cargo from being forced to re-update the
    /// registry every time it runs, and keeps the resolve in a locked state
    /// so it doesn't re-resolve the unused entries.
    unused_patches: Vec<PackageId>,
    /// A map from packages to a set of their public dependencies
    public_dependencies: HashMap<PackageId, HashSet<PackageId>>,
    /// Version of the `Cargo.lock` format, see
    /// `cargo::core::resolver::encode` for more.
    version: ResolveVersion,
    summaries: HashMap<PackageId, Summary>,
}

/// A version to indicate how a `Cargo.lock` should be serialized. Currently
/// V2 is the default when creating a new lockfile. If a V1 lockfile already
/// exists, it will stay as V1.
///
/// It's theorized that we can add more here over time to track larger changes
/// to the `Cargo.lock` format, but we've yet to see how that strategy pans out.
#[derive(PartialEq, Eq, Clone, Copy, Debug, PartialOrd, Ord)]
pub enum ResolveVersion {
    /// Historical baseline for when this abstraction was added.
    V1,
    /// A more compact format, more amenable to avoiding source-control merge
    /// conflicts. The `dependencies` arrays are compressed and checksums are
    /// listed inline. Introduced in 2019 in version 1.38. New lockfiles use
    /// V2 by default starting in 1.41.
    V2,
    /// A format that explicitly lists a `version` at the top of the file as
    /// well as changing how git dependencies are encoded. Dependencies with
    /// `branch = "master"` are no longer encoded the same way as those without
    /// branch specifiers.
    V3,
}

impl Resolve {
    pub fn new(
        graph: Graph<PackageId, HashSet<Dependency>>,
        replacements: HashMap<PackageId, PackageId>,
        features: HashMap<PackageId, Vec<InternedString>>,
        checksums: HashMap<PackageId, Option<String>>,
        metadata: Metadata,
        unused_patches: Vec<PackageId>,
        version: ResolveVersion,
        summaries: HashMap<PackageId, Summary>,
    ) -> Resolve {
        let reverse_replacements = replacements.iter().map(|(&p, &r)| (r, p)).collect();
        let public_dependencies = graph
            .iter()
            .map(|p| {
                let public_deps = graph
                    .edges(p)
                    .filter(|(_, deps)| {
                        deps.iter()
                            .any(|d| d.kind() == DepKind::Normal && d.is_public())
                    })
                    .map(|(dep_package, _)| *dep_package)
                    .collect::<HashSet<PackageId>>();

                (*p, public_deps)
            })
            .collect();

        Resolve {
            graph,
            replacements,
            features,
            checksums,
            metadata,
            unused_patches,
            reverse_replacements,
            public_dependencies,
            version,
            summaries,
        }
    }

    /// Resolves one of the paths from the given dependent package up to
    /// the root.
    pub fn path_to_top<'a>(
        &'a self,
        pkg: &'a PackageId,
    ) -> Vec<(&'a PackageId, Option<&'a HashSet<Dependency>>)> {
        self.graph.path_to_top(pkg)
    }

    pub fn register_used_patches(&mut self, patches: &[Summary]) {
        for summary in patches {
            if !self.graph.contains(&summary.package_id()) {
                self.unused_patches.push(summary.package_id())
            };
        }
    }

    pub fn merge_from(&mut self, previous: &Resolve) -> CargoResult<()> {
        // Given a previous instance of resolve, it should be forbidden to ever
        // have a checksums which *differ*. If the same package ID has differing
        // checksums, then something has gone wrong such as:
        //
        // * Something got seriously corrupted
        // * A "mirror" isn't actually a mirror as some changes were made
        // * A replacement source wasn't actually a replacement, some changes
        //   were made
        //
        // In all of these cases, we want to report an error to indicate that
        // something is awry. Normal execution (esp just using crates.io) should
        // never run into this.
        for (id, cksum) in previous.checksums.iter() {
            if let Some(mine) = self.checksums.get(id) {
                if mine == cksum {
                    continue;
                }

                // If the previous checksum wasn't calculated, the current
                // checksum is `Some`. This may indicate that a source was
                // erroneously replaced or was replaced with something that
                // desires stronger checksum guarantees than can be afforded
                // elsewhere.
                if cksum.is_none() {
                    anyhow::bail!(
                        "\
checksum for `{}` was not previously calculated, but a checksum could now \
be calculated

this could be indicative of a few possible situations:

    * the source `{}` did not previously support checksums,
      but was replaced with one that does
    * newer Cargo implementations know how to checksum this source, but this
      older implementation does not
    * the lock file is corrupt
",
                        id,
                        id.source_id()
                    )

                // If our checksum hasn't been calculated, then it could mean
                // that future Cargo figured out how to checksum something or
                // more realistically we were overridden with a source that does
                // not have checksums.
                } else if mine.is_none() {
                    anyhow::bail!(
                        "\
checksum for `{}` could not be calculated, but a checksum is listed in \
the existing lock file

this could be indicative of a few possible situations:

    * the source `{}` supports checksums,
      but was replaced with one that doesn't
    * the lock file is corrupt

unable to verify that `{0}` is the same as when the lockfile was generated
",
                        id,
                        id.source_id()
                    )

                // If the checksums aren't equal, and neither is None, then they
                // must both be Some, in which case the checksum now differs.
                // That's quite bad!
                } else {
                    anyhow::bail!(
                        "\
checksum for `{}` changed between lock files

this could be indicative of a few possible errors:

    * the lock file is corrupt
    * a replacement source in use (e.g., a mirror) returned a different checksum
    * the source itself may be corrupt in one way or another

unable to verify that `{0}` is the same as when the lockfile was generated
",
                        id
                    );
                }
            }
        }

        // Be sure to just copy over any unknown metadata.
        self.metadata = previous.metadata.clone();

        // Preserve the lockfile encoding where possible to avoid lockfile churn
        self.version = previous.version;

        Ok(())
    }

    pub fn contains<Q: ?Sized>(&self, k: &Q) -> bool
    where
        PackageId: Borrow<Q>,
        Q: Ord + Eq,
    {
        self.graph.contains(k)
    }

    pub fn sort(&self) -> Vec<PackageId> {
        self.graph.sort()
    }

    pub fn iter(&self) -> impl Iterator<Item = PackageId> + '_ {
        self.graph.iter().cloned()
    }

    pub fn deps(&self, pkg: PackageId) -> impl Iterator<Item = (PackageId, &HashSet<Dependency>)> {
        self.deps_not_replaced(pkg)
            .map(move |(id, deps)| (self.replacement(id).unwrap_or(id), deps))
    }

    pub fn deps_not_replaced(
        &self,
        pkg: PackageId,
    ) -> impl Iterator<Item = (PackageId, &HashSet<Dependency>)> {
        self.graph.edges(&pkg).map(|(id, deps)| (*id, deps))
    }

    pub fn replacement(&self, pkg: PackageId) -> Option<PackageId> {
        self.replacements.get(&pkg).cloned()
    }

    pub fn replacements(&self) -> &HashMap<PackageId, PackageId> {
        &self.replacements
    }

    pub fn features(&self, pkg: PackageId) -> &[InternedString] {
        self.features.get(&pkg).map(|v| &**v).unwrap_or(&[])
    }

    /// This is only here for legacy support, it will be removed when
    /// switching to the new feature resolver.
    pub fn features_clone(&self) -> HashMap<PackageId, Vec<InternedString>> {
        self.features.clone()
    }

    pub fn is_public_dep(&self, pkg: PackageId, dep: PackageId) -> bool {
        self.public_dependencies
            .get(&pkg)
            .map(|public_deps| public_deps.contains(&dep))
            .unwrap_or_else(|| panic!("Unknown dependency {:?} for package {:?}", dep, pkg))
    }

    pub fn query(&self, spec: &str) -> CargoResult<PackageId> {
        PackageIdSpec::query_str(spec, self.iter())
    }

    pub fn specs_to_ids(&self, specs: &[PackageIdSpec]) -> CargoResult<Vec<PackageId>> {
        specs.iter().map(|s| s.query(self.iter())).collect()
    }

    pub fn unused_patches(&self) -> &[PackageId] {
        &self.unused_patches
    }

    pub fn checksums(&self) -> &HashMap<PackageId, Option<String>> {
        &self.checksums
    }

    pub fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    pub fn extern_crate_name_and_dep_name(
        &self,
        from: PackageId,
        to: PackageId,
        to_target: &Target,
    ) -> CargoResult<(InternedString, Option<InternedString>)> {
        let empty_set: HashSet<Dependency> = HashSet::new();
        let deps = if from == to {
            &empty_set
        } else {
            self.dependencies_listed(from, to)
        };

        let target_crate_name = || (to_target.crate_name(), None);
        let mut name_pairs = deps.iter().map(|d| {
            d.explicit_name_in_toml()
                .map(|s| (s.as_str().replace("-", "_"), Some(s)))
                .unwrap_or_else(target_crate_name)
        });
        let (extern_crate_name, dep_name) = name_pairs.next().unwrap_or_else(target_crate_name);
        for (n, _) in name_pairs {
            anyhow::ensure!(
                n == extern_crate_name,
                "the crate `{}` depends on crate `{}` multiple times with different names",
                from,
                to,
            );
        }
        Ok((extern_crate_name.into(), dep_name))
    }

    fn dependencies_listed(&self, from: PackageId, to: PackageId) -> &HashSet<Dependency> {
        // We've got a dependency on `from` to `to`, but this dependency edge
        // may be affected by [replace]. If the `to` package is listed as the
        // target of a replacement (aka the key of a reverse replacement map)
        // then we try to find our dependency edge through that. If that fails
        // then we go down below assuming it's not replaced.
        //
        // Note that we don't treat `from` as if it's been replaced because
        // that's where the dependency originates from, and we only replace
        // targets of dependencies not the originator.
        if let Some(replace) = self.reverse_replacements.get(&to) {
            if let Some(deps) = self.graph.edge(&from, replace) {
                return deps;
            }
        }
        match self.graph.edge(&from, &to) {
            Some(ret) => ret,
            None => panic!("no Dependency listed for `{}` => `{}`", from, to),
        }
    }

    /// Returns the version of the encoding that's being used for this lock
    /// file.
    pub fn version(&self) -> ResolveVersion {
        self.version
    }

    pub fn set_version(&mut self, version: ResolveVersion) {
        self.version = version;
    }

    pub fn summary(&self, pkg_id: PackageId) -> &Summary {
        &self.summaries[&pkg_id]
    }
}

impl PartialEq for Resolve {
    fn eq(&self, other: &Resolve) -> bool {
        macro_rules! compare {
            ($($fields:ident)* | $($ignored:ident)*) => {
                let Resolve { $($fields,)* $($ignored: _,)* } = self;
                $($fields == &other.$fields)&&*
            }
        }
        compare! {
            // fields to compare
            graph replacements reverse_replacements features
            checksums metadata unused_patches public_dependencies summaries
            |
            // fields to ignore
            version
        }
    }
}

impl fmt::Debug for Resolve {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(fmt, "graph: {:?}", self.graph)?;
        writeln!(fmt, "\nfeatures: {{")?;
        for (pkg, features) in &self.features {
            writeln!(fmt, "  {}: {:?}", pkg, features)?;
        }
        write!(fmt, "}}")
    }
}

impl Default for ResolveVersion {
    /// The default way to encode new or updated `Cargo.lock` files.
    ///
    /// It's important that if a new version of `ResolveVersion` is added that
    /// this is not updated until *at least* the support for the version is in
    /// the stable release of Rust.
    ///
    /// This resolve version will be used for all new lock files, for example
    /// those generated by `cargo update` (update everything) or building after
    /// a `cargo new` (where no lock file previously existed). This is also used
    /// for *updated* lock files such as when a dependency is added or when a
    /// version requirement changes. In this situation Cargo's updating the lock
    /// file anyway so it takes the opportunity to bump the lock file version
    /// forward.
    fn default() -> ResolveVersion {
        ResolveVersion::V3
    }
}
<commit_msg>Update comment about ResolveVersion default version<commit_after>use super::encode::Metadata;
use crate::core::dependency::DepKind;
use crate::core::{Dependency, PackageId, PackageIdSpec, Summary, Target};
use crate::util::errors::CargoResult;
use crate::util::interning::InternedString;
use crate::util::Graph;
use std::borrow::Borrow;
use std::collections::{HashMap, HashSet};
use std::fmt;

/// Represents a fully-resolved package dependency graph. Each node in the graph
/// is a package and edges represent dependencies between packages.
///
/// Each instance of `Resolve` also understands the full set of features used
/// for each package.
pub struct Resolve {
    /// A graph, whose vertices are packages and edges are dependency specifications
    /// from `Cargo.toml`. We need a `HashSet` here because the same package
    /// might be present in both `[dependencies]` and `[build-dependencies]`.
    graph: Graph<PackageId, HashSet<Dependency>>,
    /// Replacements from the `[replace]` table.
    replacements: HashMap<PackageId, PackageId>,
    /// Inverted version of `replacements`.
    reverse_replacements: HashMap<PackageId, PackageId>,
    /// Features enabled for a given package.
    features: HashMap<PackageId, Vec<InternedString>>,
    /// Checksum for each package. A SHA256 hash of the `.crate` file used to
    /// validate the correct crate file is used. This is `None` for sources
    /// that do not use `.crate` files, like path or git dependencies.
    checksums: HashMap<PackageId, Option<String>>,
    /// "Unknown" metadata. This is a collection of extra, unrecognized data
    /// found in the `[metadata]` section of `Cargo.lock`, preserved for
    /// forwards compatibility.
    metadata: Metadata,
    /// `[patch]` entries that did not match anything, preserved in
    /// `Cargo.lock` as the `[[patch.unused]]` table array. Tracking unused
    /// patches helps prevent Cargo from being forced to re-update the
    /// registry every time it runs, and keeps the resolve in a locked state
    /// so it doesn't re-resolve the unused entries.
    unused_patches: Vec<PackageId>,
    /// A map from packages to a set of their public dependencies
    public_dependencies: HashMap<PackageId, HashSet<PackageId>>,
    /// Version of the `Cargo.lock` format, see
    /// `cargo::core::resolver::encode` for more.
    version: ResolveVersion,
    summaries: HashMap<PackageId, Summary>,
}

/// A version to indicate how a `Cargo.lock` should be serialized. Currently
/// V3 is the default when creating a new lockfile. If an old version of
/// lockfile already exists, it will stay as-is.
///
/// It's theorized that we can add more here over time to track larger changes
/// to the `Cargo.lock` format, but we've yet to see how that strategy pans out.
#[derive(PartialEq, Eq, Clone, Copy, Debug, PartialOrd, Ord)]
pub enum ResolveVersion {
    /// Historical baseline for when this abstraction was added.
    V1,
    /// A more compact format, more amenable to avoiding source-control merge
    /// conflicts. The `dependencies` arrays are compressed and checksums are
    /// listed inline. Introduced in 2019 in version 1.38. New lockfiles use
    /// V2 by default from 1.41 to 1.52.
    V2,
    /// A format that explicitly lists a `version` at the top of the file as
    /// well as changing how git dependencies are encoded. Dependencies with
    /// `branch = "master"` are no longer encoded the same way as those without
    /// branch specifiers. Introduced in 2020 in version 1.47. New lockfiles use
    /// V3 by default staring in 1.53.
    V3,
}

impl Resolve {
    pub fn new(
        graph: Graph<PackageId, HashSet<Dependency>>,
        replacements: HashMap<PackageId, PackageId>,
        features: HashMap<PackageId, Vec<InternedString>>,
        checksums: HashMap<PackageId, Option<String>>,
        metadata: Metadata,
        unused_patches: Vec<PackageId>,
        version: ResolveVersion,
        summaries: HashMap<PackageId, Summary>,
    ) -> Resolve {
        let reverse_replacements = replacements.iter().map(|(&p, &r)| (r, p)).collect();
        let public_dependencies = graph
            .iter()
            .map(|p| {
                let public_deps = graph
                    .edges(p)
                    .filter(|(_, deps)| {
                        deps.iter()
                            .any(|d| d.kind() == DepKind::Normal && d.is_public())
                    })
                    .map(|(dep_package, _)| *dep_package)
                    .collect::<HashSet<PackageId>>();

                (*p, public_deps)
            })
            .collect();

        Resolve {
            graph,
            replacements,
            features,
            checksums,
            metadata,
            unused_patches,
            reverse_replacements,
            public_dependencies,
            version,
            summaries,
        }
    }

    /// Resolves one of the paths from the given dependent package up to
    /// the root.
    pub fn path_to_top<'a>(
        &'a self,
        pkg: &'a PackageId,
    ) -> Vec<(&'a PackageId, Option<&'a HashSet<Dependency>>)> {
        self.graph.path_to_top(pkg)
    }

    pub fn register_used_patches(&mut self, patches: &[Summary]) {
        for summary in patches {
            if !self.graph.contains(&summary.package_id()) {
                self.unused_patches.push(summary.package_id())
            };
        }
    }

    pub fn merge_from(&mut self, previous: &Resolve) -> CargoResult<()> {
        // Given a previous instance of resolve, it should be forbidden to ever
        // have a checksums which *differ*. If the same package ID has differing
        // checksums, then something has gone wrong such as:
        //
        // * Something got seriously corrupted
        // * A "mirror" isn't actually a mirror as some changes were made
        // * A replacement source wasn't actually a replacement, some changes
        //   were made
        //
        // In all of these cases, we want to report an error to indicate that
        // something is awry. Normal execution (esp just using crates.io) should
        // never run into this.
        for (id, cksum) in previous.checksums.iter() {
            if let Some(mine) = self.checksums.get(id) {
                if mine == cksum {
                    continue;
                }

                // If the previous checksum wasn't calculated, the current
                // checksum is `Some`. This may indicate that a source was
                // erroneously replaced or was replaced with something that
                // desires stronger checksum guarantees than can be afforded
                // elsewhere.
                if cksum.is_none() {
                    anyhow::bail!(
                        "\
checksum for `{}` was not previously calculated, but a checksum could now \
be calculated

this could be indicative of a few possible situations:

    * the source `{}` did not previously support checksums,
      but was replaced with one that does
    * newer Cargo implementations know how to checksum this source, but this
      older implementation does not
    * the lock file is corrupt
",
                        id,
                        id.source_id()
                    )

                // If our checksum hasn't been calculated, then it could mean
                // that future Cargo figured out how to checksum something or
                // more realistically we were overridden with a source that does
                // not have checksums.
                } else if mine.is_none() {
                    anyhow::bail!(
                        "\
checksum for `{}` could not be calculated, but a checksum is listed in \
the existing lock file

this could be indicative of a few possible situations:

    * the source `{}` supports checksums,
      but was replaced with one that doesn't
    * the lock file is corrupt

unable to verify that `{0}` is the same as when the lockfile was generated
",
                        id,
                        id.source_id()
                    )

                // If the checksums aren't equal, and neither is None, then they
                // must both be Some, in which case the checksum now differs.
                // That's quite bad!
                } else {
                    anyhow::bail!(
                        "\
checksum for `{}` changed between lock files

this could be indicative of a few possible errors:

    * the lock file is corrupt
    * a replacement source in use (e.g., a mirror) returned a different checksum
    * the source itself may be corrupt in one way or another

unable to verify that `{0}` is the same as when the lockfile was generated
",
                        id
                    );
                }
            }
        }

        // Be sure to just copy over any unknown metadata.
        self.metadata = previous.metadata.clone();

        // Preserve the lockfile encoding where possible to avoid lockfile churn
        self.version = previous.version;

        Ok(())
    }

    pub fn contains<Q: ?Sized>(&self, k: &Q) -> bool
    where
        PackageId: Borrow<Q>,
        Q: Ord + Eq,
    {
        self.graph.contains(k)
    }

    pub fn sort(&self) -> Vec<PackageId> {
        self.graph.sort()
    }

    pub fn iter(&self) -> impl Iterator<Item = PackageId> + '_ {
        self.graph.iter().cloned()
    }

    pub fn deps(&self, pkg: PackageId) -> impl Iterator<Item = (PackageId, &HashSet<Dependency>)> {
        self.deps_not_replaced(pkg)
            .map(move |(id, deps)| (self.replacement(id).unwrap_or(id), deps))
    }

    pub fn deps_not_replaced(
        &self,
        pkg: PackageId,
    ) -> impl Iterator<Item = (PackageId, &HashSet<Dependency>)> {
        self.graph.edges(&pkg).map(|(id, deps)| (*id, deps))
    }

    pub fn replacement(&self, pkg: PackageId) -> Option<PackageId> {
        self.replacements.get(&pkg).cloned()
    }

    pub fn replacements(&self) -> &HashMap<PackageId, PackageId> {
        &self.replacements
    }

    pub fn features(&self, pkg: PackageId) -> &[InternedString] {
        self.features.get(&pkg).map(|v| &**v).unwrap_or(&[])
    }

    /// This is only here for legacy support, it will be removed when
    /// switching to the new feature resolver.
    pub fn features_clone(&self) -> HashMap<PackageId, Vec<InternedString>> {
        self.features.clone()
    }

    pub fn is_public_dep(&self, pkg: PackageId, dep: PackageId) -> bool {
        self.public_dependencies
            .get(&pkg)
            .map(|public_deps| public_deps.contains(&dep))
            .unwrap_or_else(|| panic!("Unknown dependency {:?} for package {:?}", dep, pkg))
    }

    pub fn query(&self, spec: &str) -> CargoResult<PackageId> {
        PackageIdSpec::query_str(spec, self.iter())
    }

    pub fn specs_to_ids(&self, specs: &[PackageIdSpec]) -> CargoResult<Vec<PackageId>> {
        specs.iter().map(|s| s.query(self.iter())).collect()
    }

    pub fn unused_patches(&self) -> &[PackageId] {
        &self.unused_patches
    }

    pub fn checksums(&self) -> &HashMap<PackageId, Option<String>> {
        &self.checksums
    }

    pub fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    pub fn extern_crate_name_and_dep_name(
        &self,
        from: PackageId,
        to: PackageId,
        to_target: &Target,
    ) -> CargoResult<(InternedString, Option<InternedString>)> {
        let empty_set: HashSet<Dependency> = HashSet::new();
        let deps = if from == to {
            &empty_set
        } else {
            self.dependencies_listed(from, to)
        };

        let target_crate_name = || (to_target.crate_name(), None);
        let mut name_pairs = deps.iter().map(|d| {
            d.explicit_name_in_toml()
                .map(|s| (s.as_str().replace("-", "_"), Some(s)))
                .unwrap_or_else(target_crate_name)
        });
        let (extern_crate_name, dep_name) = name_pairs.next().unwrap_or_else(target_crate_name);
        for (n, _) in name_pairs {
            anyhow::ensure!(
                n == extern_crate_name,
                "the crate `{}` depends on crate `{}` multiple times with different names",
                from,
                to,
            );
        }
        Ok((extern_crate_name.into(), dep_name))
    }

    fn dependencies_listed(&self, from: PackageId, to: PackageId) -> &HashSet<Dependency> {
        // We've got a dependency on `from` to `to`, but this dependency edge
        // may be affected by [replace]. If the `to` package is listed as the
        // target of a replacement (aka the key of a reverse replacement map)
        // then we try to find our dependency edge through that. If that fails
        // then we go down below assuming it's not replaced.
        //
        // Note that we don't treat `from` as if it's been replaced because
        // that's where the dependency originates from, and we only replace
        // targets of dependencies not the originator.
        if let Some(replace) = self.reverse_replacements.get(&to) {
            if let Some(deps) = self.graph.edge(&from, replace) {
                return deps;
            }
        }
        match self.graph.edge(&from, &to) {
            Some(ret) => ret,
            None => panic!("no Dependency listed for `{}` => `{}`", from, to),
        }
    }

    /// Returns the version of the encoding that's being used for this lock
    /// file.
    pub fn version(&self) -> ResolveVersion {
        self.version
    }

    pub fn set_version(&mut self, version: ResolveVersion) {
        self.version = version;
    }

    pub fn summary(&self, pkg_id: PackageId) -> &Summary {
        &self.summaries[&pkg_id]
    }
}

impl PartialEq for Resolve {
    fn eq(&self, other: &Resolve) -> bool {
        macro_rules! compare {
            ($($fields:ident)* | $($ignored:ident)*) => {
                let Resolve { $($fields,)* $($ignored: _,)* } = self;
                $($fields == &other.$fields)&&*
            }
        }
        compare! {
            // fields to compare
            graph replacements reverse_replacements features
            checksums metadata unused_patches public_dependencies summaries
            |
            // fields to ignore
            version
        }
    }
}

impl fmt::Debug for Resolve {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(fmt, "graph: {:?}", self.graph)?;
        writeln!(fmt, "\nfeatures: {{")?;
        for (pkg, features) in &self.features {
            writeln!(fmt, "  {}: {:?}", pkg, features)?;
        }
        write!(fmt, "}}")
    }
}

impl Default for ResolveVersion {
    /// The default way to encode new or updated `Cargo.lock` files.
    ///
    /// It's important that if a new version of `ResolveVersion` is added that
    /// this is not updated until *at least* the support for the version is in
    /// the stable release of Rust.
    ///
    /// This resolve version will be used for all new lock files, for example
    /// those generated by `cargo update` (update everything) or building after
    /// a `cargo new` (where no lock file previously existed). This is also used
    /// for *updated* lock files such as when a dependency is added or when a
    /// version requirement changes. In this situation Cargo's updating the lock
    /// file anyway so it takes the opportunity to bump the lock file version
    /// forward.
    fn default() -> ResolveVersion {
        ResolveVersion::V3
    }
}
<|endoftext|>


<commit_before>#![deny(unused_mut)]
extern crate zookeeper;
#[macro_use]
extern crate log;
extern crate env_logger;

use std::io;
use std::sync::Arc;
use std::time::Duration;
use std::thread;
use zookeeper::{CreateMode, Watcher, WatchedEvent, ZooKeeper};
use zookeeper::acls;

struct LoggingWatcher;
impl Watcher for LoggingWatcher {
    fn handle(&mut self, e: &WatchedEvent) {
        info!("{:?}", e)
    }
}

fn zk_example() {
    let zk = ZooKeeper::connect("localhost:2181/", Duration::from_secs(5), LoggingWatcher).unwrap();

    let mut tmp = String::new();

    let auth = zk.add_auth("digest", vec![1,2,3,4]);

    println!("authenticated -> {:?}", auth);

    let path = zk.create("/test", vec![1,2], acls::OPEN_ACL_UNSAFE.clone(), CreateMode::Ephemeral);

    println!("created -> {:?}", path);

    let exists = zk.exists("/test", true);

    println!("exists -> {:?}", exists);

    let doesnt_exist = zk.exists("/blabla", true);

    println!("don't exists path -> {:?}", doesnt_exist);

    let get_acl = zk.get_acl("/test");

    println!("get_acl -> {:?}", get_acl);

    let set_acl = zk.set_acl("/test", acls::OPEN_ACL_UNSAFE.clone(), -1);

    println!("set_acl -> {:?}", set_acl);

    let children = zk.get_children("/", true);

    println!("children of / -> {:?}", children);

    let set_data = zk.set_data("/test", vec![6,5,4,3], -1);

    println!("set_data -> {:?}", set_data);

    let get_data = zk.get_data("/test", true);

    println!("get_data -> {:?}", get_data);

    // let delete = zk.delete("/test", -1);

    // println!("deleted /test -> {:?}", delete);

    println!("press enter to close client");
    io::stdin().read_line(&mut tmp).unwrap();

    // The client can be shared between tasks
    let zk = Arc::new(zk);
    thread::spawn(move || {
        zk.close().unwrap();

        // And operations return error after closed
        match zk.exists("/test", false) {
            Err(err) => println!("Usage after closed should end up with error: {:?}", err),
            Ok(_) => panic!("Shouldn't happen")
        }
    });

    println!("press enter to exit example");
    io::stdin().read_line(&mut tmp).unwrap();
}

fn main() {
    env_logger::init().unwrap();
    zk_example();
}
<commit_msg>pick up zk url from env var, and experiment with a get children with watch<commit_after>#![deny(unused_mut)]
extern crate zookeeper;
#[macro_use]
extern crate log;
extern crate env_logger;

use std::io;
use std::sync::Arc;
use std::time::Duration;
use std::thread;
use std::env;
use zookeeper::{CreateMode, Watcher, WatchedEvent, ZooKeeper};
use zookeeper::acls;

struct LoggingWatcher;
impl Watcher for LoggingWatcher {
    fn handle(&mut self, e: &WatchedEvent) {
        info!("{:?}", e)
    }
}

fn zk_server_urls() -> String {
    let key = "ZOOKEEPER_SERVERS";
    match env::var(key) {
        Ok(val) => val,
        Err(_) => "localhost:2181".to_string(),
    }
}

fn zk_example() {
    let zk = ZooKeeper::connect(&*zk_server_urls(), Duration::from_secs(5), LoggingWatcher).unwrap();

    let mut tmp = String::new();

    let auth = zk.add_auth("digest", vec![1,2,3,4]);

    println!("authenticated -> {:?}", auth);

    let path = zk.create("/test", vec![1,2], acls::OPEN_ACL_UNSAFE.clone(), CreateMode::Ephemeral);

    println!("created -> {:?}", path);

    let exists = zk.exists("/test", true);

    println!("exists -> {:?}", exists);

    let doesnt_exist = zk.exists("/blabla", true);

    println!("don't exists path -> {:?}", doesnt_exist);

    let get_acl = zk.get_acl("/test");

    println!("get_acl -> {:?}", get_acl);

    let set_acl = zk.set_acl("/test", acls::OPEN_ACL_UNSAFE.clone(), -1);

    println!("set_acl -> {:?}", set_acl);

    let children = zk.get_children("/", true);

    println!("children of / -> {:?}", children);

    let set_data = zk.set_data("/test", vec![6,5,4,3], -1);

    println!("set_data -> {:?}", set_data);

    let get_data = zk.get_data("/test", true);

    println!("get_data -> {:?}", get_data);

    // let delete = zk.delete("/test", -1);

    // println!("deleted /test -> {:?}", delete);

    let watch_children = zk.get_children_w("/", LoggingWatcher);
    println!("watch children -> {:?}", watch_children);

    println!("press enter to close client");
    io::stdin().read_line(&mut tmp).unwrap();

    // The client can be shared between tasks
    let zk = Arc::new(zk);
    thread::spawn(move || {
        zk.close().unwrap();

        // And operations return error after closed
        match zk.exists("/test", false) {
            Err(err) => println!("Usage after closed should end up with error: {:?}", err),
            Ok(_) => panic!("Shouldn't happen")
        }
    });

    println!("press enter to exit example");
    io::stdin().read_line(&mut tmp).unwrap();
}

fn main() {
    env_logger::init().unwrap();
    zk_example();
}
<|endoftext|>


<commit_before>#![allow(clippy::vec_init_then_push)]

use std::path::PathBuf;

use xshell::pushd;

use crate::{cmd, Metadata, Result};

const MSRV: &str = "1.45";

/// Task to run CI tests.
pub struct CiTask {
    /// Which version of Rust to test against.
    version: Option<String>,

    /// The root of the workspace.
    project_root: PathBuf,
}

impl CiTask {
    pub(crate) fn new(version: Option<String>) -> Result<Self> {
        let project_root = Metadata::load()?.workspace_root;
        Ok(Self { version, project_root })
    }

    pub(crate) fn run(self) -> Result<()> {
        let _p = xshell::pushd(&self.project_root)?;

        match self.version.as_deref() {
            Some("msrv") => self.build_msrv()?,
            Some("stable") => self.build_stable()?,
            Some("nightly") => self.build_nightly()?,
            Some(_) => return Err("Wrong Rust version specified.".into()),
            None => {
                self.build_msrv().and(self.build_stable()).and(self.build_nightly())?;
            }
        }

        Ok(())
    }

    fn build_msrv(&self) -> xshell::Result<()> {
        let _p = pushd("ruma")?;
        cmd!("rustup run {MSRV} cargo build --features full --quiet").run()
    }

    fn build_stable(&self) -> xshell::Result<()> {
        let mut r = Vec::new();
        r.push(cmd!("rustup run stable cargo test --workspace --quiet").run());

        {
            let _p = pushd("ruma-identifiers")?;
            r.push(cmd!("rustup run stable cargo test --no-default-features --quiet").run());
            r.push(cmd!("rustup run stable cargo test --all-features --quiet").run());
        }

        {
            let _p = pushd("ruma-client-api");
            r.push(cmd!("rustup run stable cargo test --all-features --quiet").run());
        }

        {
            let _p = pushd("ruma-client")?;
            r.push(cmd!("rustup run stable cargo check --no-default-features --quiet").run());
            r.push(cmd!("rustup run stable cargo check --all-features --quiet").run());
        }

        r.into_iter().collect()
    }

    fn build_nightly(&self) -> xshell::Result<()> {
        let mut r = Vec::new();
        r.push(cmd!("rustup run nightly cargo fmt -- --check").run());

        {
            let _p = pushd("ruma");
            r.push(
                cmd!(
                    "rustup run nightly cargo clippy
                        --all-targets --all-features --quiet -- -D warnings"
                )
                .run(),
            );
        }

        {
            let _p = pushd("ruma-client");
            r.push(
                cmd!("rustup run nightly cargo clippy --all-targets --quiet -- -D warnings").run(),
            );
        }

        r.into_iter().collect()
    }
}
<commit_msg>xtask: Simplify code for ci task<commit_after>use std::path::PathBuf;

use xshell::pushd;

use crate::{cmd, Metadata, Result};

const MSRV: &str = "1.45";

/// Task to run CI tests.
pub struct CiTask {
    /// Which version of Rust to test against.
    version: Option<String>,

    /// The root of the workspace.
    project_root: PathBuf,
}

impl CiTask {
    pub(crate) fn new(version: Option<String>) -> Result<Self> {
        let project_root = Metadata::load()?.workspace_root;
        Ok(Self { version, project_root })
    }

    pub(crate) fn run(self) -> Result<()> {
        let _p = xshell::pushd(&self.project_root)?;

        match self.version.as_deref() {
            Some("msrv") => self.build_msrv()?,
            Some("stable") => self.build_stable()?,
            Some("nightly") => self.build_nightly()?,
            Some(_) => return Err("Wrong Rust version specified.".into()),
            None => {
                self.build_msrv().and(self.build_stable()).and(self.build_nightly())?;
            }
        }

        Ok(())
    }

    fn build_msrv(&self) -> xshell::Result<()> {
        let _p = pushd("ruma")?;
        cmd!("rustup run {MSRV} cargo build --features full --quiet").run()
    }

    fn build_stable(&self) -> xshell::Result<()> {
        vec![
            cmd!("rustup run stable cargo test --workspace --quiet").run(),
            cmd!("rustup run stable cargo test -p ruma-identifiers --no-default-features --quiet")
                .run(),
            cmd!("rustup run stable cargo test -p ruma-identifiers --all-features --quiet").run(),
            cmd!("rustup run stable cargo test -p ruma-client-api --all-features --quiet").run(),
            cmd!("rustup run stable cargo check -p ruma-client --no-default-features --quiet")
                .run(),
            cmd!("rustup run stable cargo check -p ruma-client --all-features --quiet").run(),
        ]
        .into_iter()
        .collect()
    }

    fn build_nightly(&self) -> xshell::Result<()> {
        vec![
            cmd!("rustup run nightly cargo fmt -- --check").run(),
            cmd!(
                "rustup run nightly cargo clippy -p ruma
                    --all-targets --all-features --quiet -- -D warnings"
            )
            .run(),
            cmd!(
                "rustup run nightly cargo clippy -p ruma-client
                    --all-targets --quiet -- -D warnings"
            )
            .run(),
        ]
        .into_iter()
        .collect()
    }
}
<|endoftext|>


<commit_before>//! The simplest possible implementation of the TimeSteward API.
//!
//! This implementation is unusably slow on large simulations. Its main use is to cross-check with other TimeSteward implementations to make sure they are implementing the API correctly.
//!
//!

use super::{DeterministicRandomId, SiphashIdGenerator, RowId, FieldId, Column, ExtendedTime,
            EventRng, Basics, TimeSteward, FiatEventOperationResult, ValidSince,
            TimeStewardLifetimedMethods};
use std::collections::{HashMap, BTreeMap};
use std::hash::Hash;
// use std::collections::Bound::{Included, Excluded, Unbounded};
use std::any::Any;
use std::borrow::Borrow;
use std::rc::Rc;
use std::marker::PhantomData;

#[derive (Clone)]
pub struct Steward<B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > (Steward0, Steward1, PhantomData <B::Constants>);
pub struct Snapshot<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > (
  <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Snapshot,
  <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Snapshot,
);
pub enum Mutator<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > where <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Mutator: 'a, <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Mutator: 'a {
  Form0 (& 'a mut <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Mutator),
  Form1 (& 'a mut <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Mutator),
}
pub enum PredictorAccessor<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > where <Steward0 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor: 'a, <Steward1 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor: 'a {
  Form0 (& 'a mut <Steward0 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor),
  Form1 (& 'a mut <Steward1 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor),
}
pub type Event<B, Steward0, Steward1> = Rc<for<'d, 'e> Fn(&'d mut Mutator<'e, B, Steward0, Steward1>)>;
pub type Predictor<B, Steward0, Steward1> = super::Predictor<PredictorFn<B, Steward0, Steward1>>;
pub type PredictorFn<B, Steward0, Steward1> = Rc<for<'b, 'c> Fn(&'b mut PredictorAccessor<'c, B, Steward0, Steward1>, RowId)>;

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for Snapshot<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match (self.0.get::<C> (id), self.1.get::<C> (id)) {
      (None, None) => None,
      //we cannot actually check whether the values are the same, so just use one of them
      (Some (value_0), Some (value_1)) => Some (value_0),
      //however, we CAN tell the difference between something and nothing
      _=> panic! ("One snapshot returned a value and the other didn't; this proves that one or both of the stewards is buggy")
    }
  }
  fn constants(&self) -> &B::Constants {
    //constants are usually implemented trivially; we don't bother checking them
    self.0.constants()
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for Mutator<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match self {
      Form0 (other) => other.get::<C> (id),
      Form1 (other) => other.get::<C> (id),
    }
  }
  fn constants(&self) -> &B::Constants {
    match self {
      Form0 (other) => other.constants (),
      Form1 (other) => other.constants (),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for PredictorAccessor<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match self {
      Form0 (other) => other.get::<C> (id),
      Form1 (other) => other.get::<C> (id),
    }
  }
  fn constants(&self) -> &B::Constants {
    match self {
      Form0 (other) => other.constants (),
      Form1 (other) => other.constants (),
    }
  }
}

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::MomentaryAccessor<B> for Snapshot<'a, B, Steward0, Steward1> {
  fn now(&self) -> &B::Time {
    result = (self.0.now(), self.1.now());
    assert! (result.0 == result.1, "Snapshots returned different times; this is an egregious bug!");
    result.0
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::MomentaryAccessor<B> for Mutator<'a, B, Steward0, Steward1> {
  fn now(&self) -> &B::Time {
    match self {
      Form0 (other) => other.now(),
      Form1 (other) => other.now(),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::PredictorAccessor<B> for PredictorAccessor<'a, B, Steward0, Steward1> {
  type Event = Event<B, Steward0, Steward1>;
  fn predict_immediately(&mut self, event: Event<B, Steward0, Steward1>) {
    match self {
      Form0 (other) => other.predict_immediately(time, convert_event_0 (event)),
      Form1 (other) => other.predict_immediately(time, convert_event_1 (event)),
    }
  }
  fn predict_at_time(&mut self, time: &B::Time, event: Event<B, Steward0, Steward1>) {
    match self {
      Form0 (other) => other.predict_at_time(time, convert_event_0 (event)),
      Form1 (other) => other.predict_at_time(time, convert_event_1 (event)),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Snapshot<B> for Snapshot<'a, B, Steward0, Steward1> {}

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Mutator<B> for Mutator<'a, B, Steward0, Steward1> {
  fn set<C: Column>(&mut self, id: RowId, data: Option<C::FieldType>) {
    match self {
      Form0 (other) => other.set::<C>(id, data),
      Form1 (other) => other.set::<C>(id, date),
    }
  }
  fn rng(&mut self) -> &mut EventRng {
    match self {
      Form0 (other) => other.rng (),
      Form1 (other) => other.rng (),
    }
  }
  fn random_id(&mut self) -> RowId {
    match self {
      Form0 (other) => other.random_id(),
      Form1 (other) => other.random_id(),
    }
  }
}

fn convert_event_0 <B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B>> (event: Event <B, Steward0, Steward1>)-><Steward0 as TimeSteward <B>>::Event {
  Rc::new (| mutator | {event (&mut Mutator::Form0 (mutator))});
}
fn convert_event_1 <B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B>> (event: Event <B, Steward0, Steward1>)-><Steward1 as TimeSteward <B>>::Event {
  Rc::new (| mutator | {event (&mut Mutator::Form1 (mutator))});
}

impl<'a, B: Basics, Steward0: 'a + TimeSteward<B>, Steward1: 'a + TimeSteward<B> > TimeStewardLifetimedMethods<'a, B> for Steward<B, Steward0, Steward1> {
  type Snapshot = Snapshot<'a, B, Steward0, Steward1>;
  type Mutator = Mutator <'a, B, Steward0, Steward1>;
  type PredictorAccessor = PredictorAccessor <'a, B, Steward0, Steward1>;

  fn snapshot_before(&'a mut self, time: &B::Time) -> Option<Self::Snapshot> {
    match (
      self.0.snapshot_before (time),
      self.1.snapshot_before (time)
    ) {
      (None, None) => None,
      (Some (snapshot_0), Some (snapshot_1)) => Some (Snapshot (snapshot_0, snapshot_1)),
      _=> panic! ("One steward returned a snapshot and the other didn't; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)");
    }
  }
}
impl<B: Basics, Steward0: TimeSteward<B> , Steward1: TimeSteward<B> > TimeSteward<B> for Steward<B, Steward0, Steward1> where B::Constants: Clone {
  type Event = Event<B, Steward0, Steward1>;
  type Predictor = Predictor<B, Steward0, Steward1>;

  fn valid_since(&self) -> ValidSince<B::Time> {
    unimplemented!()
  }
  fn new_empty(constants: B::Constants, predictors: Vec<Self::Predictor>) -> Self {
    Steward (
      Steward0::new_empty (constants.clone(), predictors.iter().map(| predictor | Steward0::Predictor {predictor_id: predictor. predictor_id, column_id: predictor.column_id, function: | accessor, rather | (predictor.function) (&mut PredictorAccessor::Form0 (accessor), row)).collect()),
      Steward1::new_empty (constants, predictors.iter().map(| predictor | Steward1::Predictor {predictor_id: predictor. predictor_id, column_id: predictor.column_id, function: | accessor, row | (predictor.function) (&mut PredictorAccessor::Form1 (accessor), row)).collect()),
      PhantomData,
    )
  }

  fn insert_fiat_event(&mut self,
                       time: B::Time,
                       id: DeterministicRandomId,
                       event: Self::Event)
                       -> FiatEventOperationResult {
    let result_0 = self.0.insert_fiat_event (time.clone(), id.clone(),convert_event_0 (event));
    let result_1 = self.1.insert_fiat_event (time, id, convert_event_1 (event));
    assert! (result_0 == result_1, "stewards returned different results for insert_fiat_event; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)");
  }
  fn erase_fiat_event(&mut self,
                      time: &B::Time,
                      id: DeterministicRandomId)
                      -> FiatEventOperationResult {
    let result_0 = self.0.erase_fiat_event (time, id.clone());
    let result_1 = self.1.erase_fiat_event (time, id);
    assert! (result_0 == result_1, "stewards returned different results for erase_fiat_event; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)");
  }
}
<commit_msg>Some error fixing<commit_after>//! The simplest possible implementation of the TimeSteward API.
//!
//! This implementation is unusably slow on large simulations. Its main use is to cross-check with other TimeSteward implementations to make sure they are implementing the API correctly.
//!
//!

use super::{DeterministicRandomId, SiphashIdGenerator, RowId, FieldId, Column, ExtendedTime,
            EventRng, Basics, TimeSteward, FiatEventOperationResult, ValidSince,
            TimeStewardLifetimedMethods};
use std::collections::{HashMap, BTreeMap};
use std::hash::Hash;
// use std::collections::Bound::{Included, Excluded, Unbounded};
use std::any::Any;
use std::borrow::Borrow;
use std::rc::Rc;
use std::marker::PhantomData;

#[derive (Clone)]
pub struct Steward<B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > (Steward0, Steward1, PhantomData <B::Constants>);
pub struct Snapshot<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > (
  <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Snapshot,
  <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Snapshot,
);
pub enum Mutator<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > where <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Mutator: 'a, <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Mutator: 'a {
  Form0 (& 'a mut <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Mutator),
  Form1 (& 'a mut <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Mutator),
}
pub enum PredictorAccessor<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > where <Steward0 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor: 'a, <Steward1 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor: 'a {
  Form0 (& 'a mut <Steward0 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor),
  Form1 (& 'a mut <Steward1 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor),
}
pub type Event<B, Steward0, Steward1> = Rc<for<'d, 'e> Fn(&'d mut Mutator<'e, B, Steward0, Steward1>)>;
pub type Predictor<B, Steward0, Steward1> = super::Predictor<PredictorFn<B, Steward0, Steward1>>;
pub type PredictorFn<B, Steward0, Steward1> = Rc<for<'b, 'c> Fn(&'b mut PredictorAccessor<'c, B, Steward0, Steward1>, RowId)>;

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for Snapshot<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match (self.0.get::<C> (id), self.1.get::<C> (id)) {
      (None, None) => None,
      //we cannot actually check whether the values are the same, so just use one of them
      (Some (value_0), Some (value_1)) => Some (value_0),
      //however, we CAN tell the difference between something and nothing
      _=> panic! ("One snapshot returned a value and the other didn't; this proves that one or both of the stewards is buggy")
    }
  }
  fn constants(&self) -> &B::Constants {
    //constants are usually implemented trivially; we don't bother checking them
    self.0.constants()
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for Mutator<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match self {
      &mut Mutator::Form0 (other) => other.get::<C> (id),
      &mut Mutator::Form1 (other) => other.get::<C> (id),
    }
  }
  fn constants(&self) -> &B::Constants {
    match self {
      & Mutator::Form0 (other) => other.constants (),
      & Mutator::Form1 (other) => other.constants (),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for PredictorAccessor<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match self {
      &mut PredictorAccessor::Form0 (other) => other.get::<C> (id),
      &mut PredictorAccessor::Form1 (other) => other.get::<C> (id),
    }
  }
  fn constants(&self) -> &B::Constants {
    match self {
      & PredictorAccessor::Form0 (other) => other.constants (),
      & PredictorAccessor::Form1 (other) => other.constants (),
    }
  }
}

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::MomentaryAccessor<B> for Snapshot<'a, B, Steward0, Steward1> {
  fn now(&self) -> &B::Time {
    let result = (self.0.now(), self.1.now());
    assert! (result.0 == result.1, "Snapshots returned different times; this is an egregious bug!");
    result.0
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::MomentaryAccessor<B> for Mutator<'a, B, Steward0, Steward1> {
  fn now(&self) -> &B::Time {
    match self {
      & Mutator::Form0 (other) => other.now(),
      & Mutator::Form1 (other) => other.now(),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::PredictorAccessor<B> for PredictorAccessor<'a, B, Steward0, Steward1> {
  type Event = Event<B, Steward0, Steward1>;
  fn predict_immediately(&mut self, event: Event<B, Steward0, Steward1>) {
    match self {
      &mut PredictorAccessor::Form0 (other) => other.predict_immediately(convert_event_0 (event)),
      &mut PredictorAccessor::Form1 (other) => other.predict_immediately(convert_event_1 (event)),
    }
  }
  fn predict_at_time(&mut self, time: &B::Time, event: Event<B, Steward0, Steward1>) {
    match self {
      &mut PredictorAccessor::Form0 (other) => other.predict_at_time(time, convert_event_0 (event)),
      &mut PredictorAccessor::Form1 (other) => other.predict_at_time(time, convert_event_1 (event)),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Snapshot<B> for Snapshot<'a, B, Steward0, Steward1> {}

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Mutator<B> for Mutator<'a, B, Steward0, Steward1> {
  fn set<C: Column>(&mut self, id: RowId, data: Option<C::FieldType>) {
    match self {
      &mut Mutator::Form0 (other) => other.set::<C>(id, data),
      &mut Mutator::Form1 (other) => other.set::<C>(id, data),
    }
  }
  fn rng(&mut self) -> &mut EventRng {
    match self {
      &mut Mutator::Form0 (other) => other.rng (),
      &mut Mutator::Form1 (other) => other.rng (),
    }
  }
  fn random_id(&mut self) -> RowId {
    match self {
      &mut Mutator::Form0 (other) => other.random_id(),
      &mut Mutator::Form1 (other) => other.random_id(),
    }
  }
}

fn convert_event_0 <B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B>> (event: Event <B, Steward0, Steward1>)-><Steward0 as TimeSteward <B>>::Event {
  Rc::new (| mutator | {event (&mut Mutator::Form0 (mutator))});
}
fn convert_event_1 <B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B>> (event: Event <B, Steward0, Steward1>)-><Steward1 as TimeSteward <B>>::Event {
  Rc::new (| mutator | {event (&mut Mutator::Form1 (mutator))});
}

impl<'a, B: Basics, Steward0: 'a + TimeSteward<B>, Steward1: 'a + TimeSteward<B> > TimeStewardLifetimedMethods<'a, B> for Steward<B, Steward0, Steward1> {
  type Snapshot = Snapshot<'a, B, Steward0, Steward1>;
  type Mutator = Mutator <'a, B, Steward0, Steward1>;
  type PredictorAccessor = PredictorAccessor <'a, B, Steward0, Steward1>;

  fn snapshot_before(&'a mut self, time: &B::Time) -> Option<Self::Snapshot> {
    match (
      self.0.snapshot_before (time),
      self.1.snapshot_before (time)
    ) {
      (None, None) => None,
      (Some (snapshot_0), Some (snapshot_1)) => Some (Snapshot (snapshot_0, snapshot_1)),
      _=> panic! ("One steward returned a snapshot and the other didn't; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)")
    }
  }
}
impl<B: Basics, Steward0: TimeSteward<B> , Steward1: TimeSteward<B> > TimeSteward<B> for Steward<B, Steward0, Steward1> where B::Constants: Clone {
  type Event = Event<B, Steward0, Steward1>;
  type Predictor = Predictor<B, Steward0, Steward1>;

  fn valid_since(&self) -> ValidSince<B::Time> {
    unimplemented!()
  }
  fn new_empty(constants: B::Constants, predictors: Vec<Self::Predictor>) -> Self {
    Steward (
      Steward0::new_empty (constants.clone(), predictors.iter().map(| predictor | Steward0::Predictor {predictor_id: predictor. predictor_id, column_id: predictor.column_id, function: | accessor, row | (predictor.function) (&mut PredictorAccessor::Form0 (accessor), row)}).collect()),
      Steward1::new_empty (constants, predictors.iter().map(| predictor | Steward1::Predictor {predictor_id: predictor. predictor_id, column_id: predictor.column_id, function: | accessor, row | (predictor.function) (&mut PredictorAccessor::Form1 (accessor), row)}).collect()),
      PhantomData,
    )
  }

  fn insert_fiat_event(&mut self,
                       time: B::Time,
                       id: DeterministicRandomId,
                       event: Self::Event)
                       -> FiatEventOperationResult {
    let result_0 = self.0.insert_fiat_event (time.clone(), id.clone(),convert_event_0 (event));
    let result_1 = self.1.insert_fiat_event (time, id, convert_event_1 (event));
    assert! (result_0 == result_1, "stewards returned different results for insert_fiat_event; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)");
    result_0
  }
  fn erase_fiat_event(&mut self,
                      time: &B::Time,
                      id: DeterministicRandomId)
                      -> FiatEventOperationResult {
    let result_0 = self.0.erase_fiat_event (time, id.clone());
    let result_1 = self.1.erase_fiat_event (time, id);
    assert! (result_0 == result_1, "stewards returned different results for erase_fiat_event; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)");
    result_0
  }
}
<|endoftext|>