<commit_before>//! A generator for structs that can easily be converted to/from arrays and
//! slices.

/// The `struct_array!` macro generates a `struct` that can be easily converted
/// to/from arrays and slices.
///
/// The format of the macro is similar to a normal struct definition, as shown
/// in the example below. The only differences are an annotation after the
/// struct name for the member type and number of members, and the lack of type
/// annotations on individual members.
///
/// The members of the struct must all be the same type, and the **number of
/// members must be specified correctly**. As long as the number of members is
/// specified correctly, I think everything is safe.
///
/// # Example
///
/// ```
/// #[macro_use]
/// extern crate struct_array;
///
/// struct_array! {
///     /// Example struct array.
///     #[derive(Clone,Debug,PartialEq)]
///     struct Example[u32; 2] {
///         /// x member
///         pub x,
///         /// y member
///         pub y,
///     }
/// }
///
/// fn main() {
///     // Deref as an array.
///     {
///         let example = Example { x: 42, y: 56 };
///         let array: &[u32; 2] = &example;
///         assert_eq!(array, &[42, 56]);
///     }
///
///     // Deref as a slice (via derefing as an array).
///     {
///         let example = Example { x: 42, y: 56 };
///         let slice: &[u32] = &*example;
///         assert_eq!(slice, &[42, 56]);
///     }
///
///     // Convert into an array.
///     {
///         let example = Example { x: 42, y: 56 };
///         let array: [u32; 2] = example.into();
///         assert_eq!(array, [42, 56]);
///     }
///
///     // Convert from an array to a struct.
///     {
///         let array = [42, 56];
///         let example: Example = array.into();
///         assert_eq!(example, Example { x: 42, y: 56 });
///     }
///
///     // Convert from a slice to a struct reference.
///     {
///         let slice = &[42, 56][..];
///         let example: &Example = slice.into();
///         assert_eq!(example, &Example { x: 42, y: 56 });
///     }
/// }
///
/// ```
///
/// # Attributes
///
/// The generated struct is `repr(C)`. Additional attributes can be attached to
/// the generated `struct` as shown in the example.
///
/// # Visibility
///
/// Members of the generated struct are always `pub`, but the struct itself is
/// not `pub` by default. The struct definition can be made `pub` by adding
/// `pub` before `struct`:
///
/// ```ignore
/// #[macro_use]
/// extern crate struct_array;
///
/// mod example {
///     struct_array! {
///         pub struct Example1[u32; 2] {
///             pub x,
///             pub y,
///         }
///     }
///
///     struct_array! {
///         struct Example2[u32; 2] {
///             pub x,
///             pub y,
///         }
///     }
/// }
///
/// fn main() {
///     let example1 = example::Example1 { x: 42, y: 56 };
///     let example2 = example::Example2 { x: 42, y: 56 }; // error: struct `Example2` is private.
/// }
/// ```
///
/// # Trait implementations
///
/// The struct generated by `struct_array! { struct Foo[T; len] { .. } }`
/// implements:
///
/// * `Deref<Target=[T; len]> for Foo`
/// * `DerefMut<Target=[T; len]> for Foo`
/// * `Into<[T; len] for Foo`
/// * `From<[T; len]> for Foo`
/// * `Into<&[T; len] for &Foo`
/// * `From<&[T; len] for &Foo`
/// * `Into<&mut [T; len] for &mut Foo`
/// * `From<&mut [T; len] for &mut Foo`
/// * `Into<&[T]> for &Foo`
/// * `From<&[T]> for &Foo`
/// * `Into<&mut [T]> for &mut Foo`
/// * `From<&mut [T]> for &mut Foo`
///
/// Note that converting from a slice will panic if the `len()` of the slice
/// does not must match the `len` specified for the struct. You can derive or
/// implement additional traits as for normal structs.
#[macro_export]
macro_rules! struct_array {
    (
        $( #[$attr:meta] )*
        pub struct $name:ident[$member_type:ident; $member_count:expr] {
            $(
                $( #[$member_attr:meta] )*
                pub $member:ident
            ),+
        }
    ) => {
        $( #[$attr] )*
        #[repr(C)]
        pub struct $name {
            $(
                $( #[$member_attr] )*
                pub $member: $member_type,
            )+
        }

        struct_array! {
            @_impl struct
                $name[$member_type; $member_count] {
                    $( $member ),+
                }
        }
    };
    (
        $( #[$attr:meta] )*
        struct $name:ident[$member_type:ident; $member_count:expr] {
            $(
                $( #[$member_attr:meta] )*
                pub $member:ident
            ),+
        }
    ) => {
        $( #[$attr] )*
        #[repr(C)]
        struct $name {
            $(
                $( #[$member_attr] )*
                pub $member: $member_type,
            )+
        }

        struct_array! {
            @_impl struct
                $name[$member_type; $member_count] {
                    $( $member ),+
                }
        }
    };
    (
        $( #[$attr:meta] )*
        pub struct $name:ident[$member_type:ident; $member_count:expr] {
            $(
                $( #[$member_attr:meta] )*
                pub $member:ident
            ),+,
        }
    ) => {
        $( #[$attr] )*
        #[repr(C)]
        pub struct $name {
            $(
                $( #[$member_attr] )*
                pub $member: $member_type,
            )+
        }

        struct_array! {
            @_impl struct
                $name[$member_type; $member_count] {
                    $( $member ),+
                }
        }
    };
    (
        $( #[$attr:meta] )*
        struct $name:ident[$member_type:ident; $member_count:expr] {
            $(
                $( #[$member_attr:meta] )*
                pub $member:ident
            ),+,
        }
    ) => {
        $( #[$attr] )*
        #[repr(C)]
        struct $name {
            $(
                $( #[$member_attr] )*
                pub $member: $member_type,
            )+
        }

        struct_array! {
            @_impl struct
                $name[$member_type; $member_count] {
                    $( $member ),+
                }
        }
    };
    (
        @_impl struct $name:ident[$member_type:ident; $member_count:expr] {
            $( $member:ident ),+
        }
    ) => {
        impl ::std::ops::Deref for $name {
            type Target = [$member_type; $member_count];

            fn deref(&self) -> &[$member_type; $member_count] {
                unsafe {
                    &*(self as *const $name as *const [$member_type; $member_count])
                }
            }
        }

        impl ::std::ops::DerefMut for $name {
            fn deref_mut(&mut self) -> &mut [$member_type; $member_count] {
                unsafe {
                    &mut *(self as *mut $name as *mut [$member_type; $member_count])
                }
            }
        }

        impl Into<[$member_type; $member_count]> for $name {
            fn into(self) -> [$member_type; $member_count] {
                unsafe {
                    ::std::mem::transmute(self)
                }
            }
        }

        impl From<[$member_type; $member_count]> for $name {
            fn from(array: [$member_type; $member_count]) -> $name {
                unsafe {
                    ::std::mem::transmute(array)
                }
            }
        }

        impl<'a> Into<&'a [$member_type; $member_count]> for &'a $name {
            fn into(self) -> &'a [$member_type; $member_count] {
                unsafe {
                    &*(self as *const $name as *const [$member_type; $member_count])
                }
            }
        }

        impl<'a> From<&'a [$member_type; $member_count]> for &'a $name {
            fn from(array: &[$member_type; $member_count]) -> &$name {
                unsafe {
                    &*(array as *const [$member_type; $member_count] as *const $name)
                }
            }
        }

        impl<'a> Into<&'a mut [$member_type; $member_count]> for &'a mut $name {
            fn into(self) -> &'a mut [$member_type; $member_count] {
                unsafe {
                    &mut *(self as *mut $name as *mut [$member_type; $member_count])
                }
            }
        }

        impl<'a> From<&'a mut [$member_type; $member_count]> for &'a mut $name {
            fn from(array: &mut [$member_type; $member_count]) -> &mut $name {
                unsafe {
                    &mut *(array as *mut [$member_type; $member_count] as *mut $name)
                }
            }
        }

        impl<'a> Into<&'a [$member_type]> for &'a $name {
            fn into(self) -> &'a [$member_type] {
                unsafe {
                    ::std::slice::from_raw_parts(self as *const $name as *const $member_type, $member_count)
                }
            }
        }

        impl<'a> From<&'a [$member_type]> for &'a $name {
            fn from(slice: &'a [$member_type]) -> &'a $name {
                assert!(slice.len() == $member_count);
                unsafe {
                    &*(slice.as_ptr() as *const $name)
                }
            }
        }

        impl<'a> Into<&'a mut [$member_type]> for &'a mut $name {
            fn into(self) -> &'a mut [$member_type] {
                unsafe {
                    ::std::slice::from_raw_parts_mut(self as *mut $name as *mut $member_type, $member_count)
                }
            }
        }

        impl<'a> From<&'a mut [$member_type]> for &'a mut $name {
            fn from(slice: &'a mut [$member_type]) -> &'a mut $name {
                assert!(slice.len() == $member_count);
                unsafe {
                    &mut *(slice.as_mut_ptr() as *mut $name)
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    struct_array! {
        /// Example struct array.
        #[derive(Clone,Debug,PartialEq)]
        struct Example[u32; 2] {
            /// x member
            pub x,
            /// y member
            pub y,
        }
    }

    #[test]
    fn test_deref() {
        let foo = Example {
            x: 0,
            y: 1,
        };
        let bar: &[u32; 2] = &foo;
        assert_eq!(bar, &[0, 1]);
    }

    #[test]
    fn test_deref_mut() {
        let mut foo = Example {
            x: 0,
            y: 1,
        };
        {
            let bar: &mut [u32; 2] = &mut foo;
            bar[1] = 2;
            assert_eq!(bar, &[0, 2]);
        }
        assert_eq!(foo, Example { x: 0, y: 2 });
    }

    #[test]
    fn test_into_array() {
        let foo = Example { x: 0, y: 1 };
        let bar: [u32; 2] = foo.into();
        assert_eq!(bar, [0, 1]);
    }

    #[test]
    fn test_from_array() {
        let foo = [0, 1];
        let mut bar: Example = foo.into();
        bar.y = 2;
        assert_eq!(bar, Example { x: 0, y: 2 });
    }

    #[test]
    fn test_into_array_ref() {
        let foo = &Example { x: 0, y: 1 };
        let bar: &[u32; 2] = foo.into();
        assert_eq!(bar, &[0, 1]);
    }

    #[test]
    fn test_from_array_ref() {
        let foo = &[0, 1];
        let bar: &Example = foo.into();
        assert_eq!(bar, &Example { x: 0, y: 1 });
    }

    #[test]
    fn test_into_array_ref_mut() {
        let mut foo = &mut Example { x: 0, y: 1 };
        {
            let mut bar: &mut [u32; 2] = foo.into();
            bar[1] = 2;
            assert_eq!(bar, &mut [0, 2]);
        }
        assert_eq!(foo, &mut Example { x: 0, y: 2 });
    }

    #[test]
    fn test_from_array_ref_mut() {
        let foo = &mut [0, 1];
        {
            let mut bar: &mut Example = foo.into();
            bar.y = 2;
            assert_eq!(bar, &mut Example { x: 0, y: 2 });
        }
        assert_eq!(foo, &mut [0, 2]);
    }

    #[test]
    fn test_into_slice() {
        let foo = Example { x: 0, y: 1 };
        let bar: &[u32] = (&foo).into();
        assert_eq!(bar, [0, 1]);
    }

    #[test]
    fn test_from_slice() {
        let foo = [0, 1];
        let bar: &[u32] = &foo;
        let baz: &Example = bar.into();
        assert_eq!(baz, &Example { x: 0, y: 1 });
    }

    #[test]
    fn test_into_mut_slice() {
        let mut foo = Example { x: 0, y: 1 };
        {
            let bar: &mut [u32] = (&mut foo).into();
            bar[1] = 2;
            assert_eq!(bar, &mut [0, 2]);
        }
        assert_eq!(foo, Example { x: 0, y: 2 });
    }

    #[test]
    fn test_from_mut_slice() {
        let mut foo = [0, 1];
        {
            let mut bar: &mut [u32] = &mut foo;
            let mut baz: &mut Example = bar.into();
            baz.y = 2;
            assert_eq!(baz, &Example { x: 0, y: 2 });
        }
        assert_eq!(foo, [0, 2]);
    }
}
<commit_msg>Add indexing to example in docs<commit_after>//! A generator for structs that can easily be converted to/from arrays and
//! slices.

/// The `struct_array!` macro generates a `struct` that can be easily converted
/// to/from arrays and slices.
///
/// The format of the macro is similar to a normal struct definition, as shown
/// in the example below. The only differences are an annotation after the
/// struct name for the member type and number of members, and the lack of type
/// annotations on individual members.
///
/// The members of the struct must all be the same type, and the **number of
/// members must be specified correctly**. As long as the number of members is
/// specified correctly, I think everything is safe.
///
/// # Example
///
/// ```
/// #[macro_use]
/// extern crate struct_array;
///
/// struct_array! {
///     /// Example struct array.
///     #[derive(Clone,Debug,PartialEq)]
///     struct Example[u32; 2] {
///         /// x member
///         pub x,
///         /// y member
///         pub y,
///     }
/// }
///
/// fn main() {
///     // Deref as an array.
///     {
///         let example = Example { x: 42, y: 56 };
///         let array: &[u32; 2] = &example;
///         assert_eq!(array, &[42, 56]);
///     }
///
///     // Deref as a slice (via derefing as an array).
///     {
///         let example = Example { x: 42, y: 56 };
///         let slice: &[u32] = &*example;
///         assert_eq!(slice, &[42, 56]);
///     }
///
///     // Index (via derefing as an array).
///     {
///         let mut example = Example { x: 42, y: 56 };
///         example[1] = 23;
///         assert_eq!(example, Example { x: 42, y: 23 });
///     }
///
///     // Convert into an array.
///     {
///         let example = Example { x: 42, y: 56 };
///         let array: [u32; 2] = example.into();
///         assert_eq!(array, [42, 56]);
///     }
///
///     // Convert from an array to a struct.
///     {
///         let array = [42, 56];
///         let example: Example = array.into();
///         assert_eq!(example, Example { x: 42, y: 56 });
///     }
///
///     // Convert from a slice to a struct reference.
///     {
///         let slice = &[42, 56][..];
///         let example: &Example = slice.into();
///         assert_eq!(example, &Example { x: 42, y: 56 });
///     }
/// }
///
/// ```
///
/// # Attributes
///
/// The generated struct is `repr(C)`. Additional attributes can be attached to
/// the generated `struct` as shown in the example.
///
/// # Visibility
///
/// Members of the generated struct are always `pub`, but the struct itself is
/// not `pub` by default. The struct definition can be made `pub` by adding
/// `pub` before `struct`:
///
/// ```ignore
/// #[macro_use]
/// extern crate struct_array;
///
/// mod example {
///     struct_array! {
///         pub struct Example1[u32; 2] {
///             pub x,
///             pub y,
///         }
///     }
///
///     struct_array! {
///         struct Example2[u32; 2] {
///             pub x,
///             pub y,
///         }
///     }
/// }
///
/// fn main() {
///     let example1 = example::Example1 { x: 42, y: 56 };
///     let example2 = example::Example2 { x: 42, y: 56 }; // error: struct `Example2` is private.
/// }
/// ```
///
/// # Trait implementations
///
/// The struct generated by `struct_array! { struct Foo[T; len] { .. } }`
/// implements:
///
/// * `Deref<Target=[T; len]> for Foo`
/// * `DerefMut<Target=[T; len]> for Foo`
/// * `Into<[T; len] for Foo`
/// * `From<[T; len]> for Foo`
/// * `Into<&[T; len] for &Foo`
/// * `From<&[T; len] for &Foo`
/// * `Into<&mut [T; len] for &mut Foo`
/// * `From<&mut [T; len] for &mut Foo`
/// * `Into<&[T]> for &Foo`
/// * `From<&[T]> for &Foo`
/// * `Into<&mut [T]> for &mut Foo`
/// * `From<&mut [T]> for &mut Foo`
///
/// Note that converting from a slice will panic if the `len()` of the slice
/// does not must match the `len` specified for the struct. You can derive or
/// implement additional traits as for normal structs.
#[macro_export]
macro_rules! struct_array {
    (
        $( #[$attr:meta] )*
        pub struct $name:ident[$member_type:ident; $member_count:expr] {
            $(
                $( #[$member_attr:meta] )*
                pub $member:ident
            ),+
        }
    ) => {
        $( #[$attr] )*
        #[repr(C)]
        pub struct $name {
            $(
                $( #[$member_attr] )*
                pub $member: $member_type,
            )+
        }

        struct_array! {
            @_impl struct
                $name[$member_type; $member_count] {
                    $( $member ),+
                }
        }
    };
    (
        $( #[$attr:meta] )*
        struct $name:ident[$member_type:ident; $member_count:expr] {
            $(
                $( #[$member_attr:meta] )*
                pub $member:ident
            ),+
        }
    ) => {
        $( #[$attr] )*
        #[repr(C)]
        struct $name {
            $(
                $( #[$member_attr] )*
                pub $member: $member_type,
            )+
        }

        struct_array! {
            @_impl struct
                $name[$member_type; $member_count] {
                    $( $member ),+
                }
        }
    };
    (
        $( #[$attr:meta] )*
        pub struct $name:ident[$member_type:ident; $member_count:expr] {
            $(
                $( #[$member_attr:meta] )*
                pub $member:ident
            ),+,
        }
    ) => {
        $( #[$attr] )*
        #[repr(C)]
        pub struct $name {
            $(
                $( #[$member_attr] )*
                pub $member: $member_type,
            )+
        }

        struct_array! {
            @_impl struct
                $name[$member_type; $member_count] {
                    $( $member ),+
                }
        }
    };
    (
        $( #[$attr:meta] )*
        struct $name:ident[$member_type:ident; $member_count:expr] {
            $(
                $( #[$member_attr:meta] )*
                pub $member:ident
            ),+,
        }
    ) => {
        $( #[$attr] )*
        #[repr(C)]
        struct $name {
            $(
                $( #[$member_attr] )*
                pub $member: $member_type,
            )+
        }

        struct_array! {
            @_impl struct
                $name[$member_type; $member_count] {
                    $( $member ),+
                }
        }
    };
    (
        @_impl struct $name:ident[$member_type:ident; $member_count:expr] {
            $( $member:ident ),+
        }
    ) => {
        impl ::std::ops::Deref for $name {
            type Target = [$member_type; $member_count];

            fn deref(&self) -> &[$member_type; $member_count] {
                unsafe {
                    &*(self as *const $name as *const [$member_type; $member_count])
                }
            }
        }

        impl ::std::ops::DerefMut for $name {
            fn deref_mut(&mut self) -> &mut [$member_type; $member_count] {
                unsafe {
                    &mut *(self as *mut $name as *mut [$member_type; $member_count])
                }
            }
        }

        impl Into<[$member_type; $member_count]> for $name {
            fn into(self) -> [$member_type; $member_count] {
                unsafe {
                    ::std::mem::transmute(self)
                }
            }
        }

        impl From<[$member_type; $member_count]> for $name {
            fn from(array: [$member_type; $member_count]) -> $name {
                unsafe {
                    ::std::mem::transmute(array)
                }
            }
        }

        impl<'a> Into<&'a [$member_type; $member_count]> for &'a $name {
            fn into(self) -> &'a [$member_type; $member_count] {
                unsafe {
                    &*(self as *const $name as *const [$member_type; $member_count])
                }
            }
        }

        impl<'a> From<&'a [$member_type; $member_count]> for &'a $name {
            fn from(array: &[$member_type; $member_count]) -> &$name {
                unsafe {
                    &*(array as *const [$member_type; $member_count] as *const $name)
                }
            }
        }

        impl<'a> Into<&'a mut [$member_type; $member_count]> for &'a mut $name {
            fn into(self) -> &'a mut [$member_type; $member_count] {
                unsafe {
                    &mut *(self as *mut $name as *mut [$member_type; $member_count])
                }
            }
        }

        impl<'a> From<&'a mut [$member_type; $member_count]> for &'a mut $name {
            fn from(array: &mut [$member_type; $member_count]) -> &mut $name {
                unsafe {
                    &mut *(array as *mut [$member_type; $member_count] as *mut $name)
                }
            }
        }

        impl<'a> Into<&'a [$member_type]> for &'a $name {
            fn into(self) -> &'a [$member_type] {
                unsafe {
                    ::std::slice::from_raw_parts(self as *const $name as *const $member_type, $member_count)
                }
            }
        }

        impl<'a> From<&'a [$member_type]> for &'a $name {
            fn from(slice: &'a [$member_type]) -> &'a $name {
                assert!(slice.len() == $member_count);
                unsafe {
                    &*(slice.as_ptr() as *const $name)
                }
            }
        }

        impl<'a> Into<&'a mut [$member_type]> for &'a mut $name {
            fn into(self) -> &'a mut [$member_type] {
                unsafe {
                    ::std::slice::from_raw_parts_mut(self as *mut $name as *mut $member_type, $member_count)
                }
            }
        }

        impl<'a> From<&'a mut [$member_type]> for &'a mut $name {
            fn from(slice: &'a mut [$member_type]) -> &'a mut $name {
                assert!(slice.len() == $member_count);
                unsafe {
                    &mut *(slice.as_mut_ptr() as *mut $name)
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    struct_array! {
        /// Example struct array.
        #[derive(Clone,Debug,PartialEq)]
        struct Example[u32; 2] {
            /// x member
            pub x,
            /// y member
            pub y,
        }
    }

    #[test]
    fn test_deref() {
        let foo = Example {
            x: 0,
            y: 1,
        };
        let bar: &[u32; 2] = &foo;
        assert_eq!(bar, &[0, 1]);
    }

    #[test]
    fn test_deref_mut() {
        let mut foo = Example {
            x: 0,
            y: 1,
        };
        {
            let bar: &mut [u32; 2] = &mut foo;
            bar[1] = 2;
            assert_eq!(bar, &[0, 2]);
        }
        assert_eq!(foo, Example { x: 0, y: 2 });
    }

    #[test]
    fn test_into_array() {
        let foo = Example { x: 0, y: 1 };
        let bar: [u32; 2] = foo.into();
        assert_eq!(bar, [0, 1]);
    }

    #[test]
    fn test_from_array() {
        let foo = [0, 1];
        let mut bar: Example = foo.into();
        bar.y = 2;
        assert_eq!(bar, Example { x: 0, y: 2 });
    }

    #[test]
    fn test_into_array_ref() {
        let foo = &Example { x: 0, y: 1 };
        let bar: &[u32; 2] = foo.into();
        assert_eq!(bar, &[0, 1]);
    }

    #[test]
    fn test_from_array_ref() {
        let foo = &[0, 1];
        let bar: &Example = foo.into();
        assert_eq!(bar, &Example { x: 0, y: 1 });
    }

    #[test]
    fn test_into_array_ref_mut() {
        let mut foo = &mut Example { x: 0, y: 1 };
        {
            let mut bar: &mut [u32; 2] = foo.into();
            bar[1] = 2;
            assert_eq!(bar, &mut [0, 2]);
        }
        assert_eq!(foo, &mut Example { x: 0, y: 2 });
    }

    #[test]
    fn test_from_array_ref_mut() {
        let foo = &mut [0, 1];
        {
            let mut bar: &mut Example = foo.into();
            bar.y = 2;
            assert_eq!(bar, &mut Example { x: 0, y: 2 });
        }
        assert_eq!(foo, &mut [0, 2]);
    }

    #[test]
    fn test_into_slice() {
        let foo = Example { x: 0, y: 1 };
        let bar: &[u32] = (&foo).into();
        assert_eq!(bar, [0, 1]);
    }

    #[test]
    fn test_from_slice() {
        let foo = [0, 1];
        let bar: &[u32] = &foo;
        let baz: &Example = bar.into();
        assert_eq!(baz, &Example { x: 0, y: 1 });
    }

    #[test]
    fn test_into_mut_slice() {
        let mut foo = Example { x: 0, y: 1 };
        {
            let bar: &mut [u32] = (&mut foo).into();
            bar[1] = 2;
            assert_eq!(bar, &mut [0, 2]);
        }
        assert_eq!(foo, Example { x: 0, y: 2 });
    }

    #[test]
    fn test_from_mut_slice() {
        let mut foo = [0, 1];
        {
            let mut bar: &mut [u32] = &mut foo;
            let mut baz: &mut Example = bar.into();
            baz.y = 2;
            assert_eq!(baz, &Example { x: 0, y: 2 });
        }
        assert_eq!(foo, [0, 2]);
    }
}
<|endoftext|>


<commit_before>#[test]
fn it_works() {
}
<commit_msg>Initial implementation.<commit_after>use std::collections::HashSet;
use std::hash::Hash;

struct UniqueState<I>
    where I: Iterator
{
    seen: HashSet<I::Item>,
    underlying: I,
}

trait Unique: Iterator {
    fn unique(self) -> UniqueState<Self>
        where Self::Item: Hash + Eq + Clone,
              Self: Sized,
    {
        UniqueState { seen: HashSet::new(), underlying: self }
    }
}

impl<I> Unique for I where I: Iterator {}

impl<I> Iterator for UniqueState<I>
    where I: Iterator,
          I::Item: Hash + Eq + Clone,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(x) = self.underlying.next() {
            if !self.seen.contains(&x) {
                self.seen.insert(x.clone());
                return Some(x)
            }
        }
        None
    }
}
#[test]
fn it_works() {
}
<|endoftext|>


<commit_before>#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]

#[cfg(feature = "printing")]
#[macro_use]
extern crate quote;

#[cfg(feature = "pretty")]
extern crate syntex_syntax as syntax;

#[cfg(feature = "parsing")]
extern crate unicode_xid;

#[cfg(feature = "parsing")]
#[macro_use]
mod nom;

#[cfg(feature = "parsing")]
#[macro_use]
mod helper;

#[cfg(feature = "parsing")]
mod escape;

mod attr;
pub use attr::{Attribute, AttrStyle, MetaItem, NestedMetaItem};

mod constant;
pub use constant::ConstExpr;

mod data;
pub use data::{Field, Variant, VariantData, Visibility};

#[cfg(feature = "full")]
mod expr;
#[cfg(feature = "full")]
pub use expr::{Arm, BindingMode, Block, BlockCheckMode, CaptureBy, Expr, ExprKind, FieldPat, Local,
               MacStmtStyle, Pat, RangeLimits, Stmt};

mod generics;
pub use generics::{Generics, Lifetime, LifetimeDef, TraitBoundModifier, TyParam, TyParamBound,
                   WhereBoundPredicate, WhereClause, WherePredicate, WhereRegionPredicate};
#[cfg(feature = "printing")]
pub use generics::{ImplGenerics, TyGenerics};

#[cfg(feature = "full")]
mod krate;
#[cfg(feature = "full")]
pub use krate::Crate;

mod ident;
pub use ident::Ident;

#[cfg(feature = "full")]
mod item;
#[cfg(feature = "full")]
pub use item::{Constness, Defaultness, FnArg, FnDecl, ForeignItemKind, ForeignItem, ForeignMod,
               ImplItem, ImplItemKind, ImplPolarity, Item, ItemKind, MethodSig, PathListItem,
               TraitItem, TraitItemKind, ViewPath};

mod lit;
pub use lit::{FloatTy, IntTy, Lit, StrStyle};

#[cfg(feature = "full")]
mod mac;
#[cfg(feature = "full")]
pub use mac::{BinOpToken, DelimToken, Delimited, Mac, Token, TokenTree};

mod macro_input;
pub use macro_input::{Body, MacroInput};

mod op;
pub use op::{BinOp, UnOp};

#[cfg(feature = "expand")]
mod registry;
#[cfg(feature = "expand")]
pub use registry::{CustomDerive, Expanded, Registry};

#[cfg(feature = "parsing")]
mod space;

mod ty;
pub use ty::{Abi, AngleBracketedParameterData, BareFnArg, BareFnTy, FunctionRetTy, MutTy,
             Mutability, ParenthesizedParameterData, Path, PathParameters, PathSegment,
             PolyTraitRef, QSelf, Ty, TypeBinding, Unsafety};

#[cfg(feature = "aster")]
pub mod aster;

#[cfg(feature = "visit")]
pub mod visit;

#[cfg(feature = "parsing")]
pub use parsing::*;

#[cfg(feature = "parsing")]
mod parsing {
    use super::*;
    use {generics, macro_input, space, ty};
    use nom::IResult;

    #[cfg(feature = "full")]
    use {expr, item, krate, mac};

    pub fn parse_macro_input(input: &str) -> Result<MacroInput, String> {
        unwrap("macro input", macro_input::parsing::macro_input, input)
    }

    #[cfg(feature = "full")]
    pub fn parse_crate(input: &str) -> Result<Crate, String> {
        unwrap("crate", krate::parsing::krate, input)
    }

    #[cfg(feature = "full")]
    pub fn parse_item(input: &str) -> Result<Item, String> {
        unwrap("item", item::parsing::item, input)
    }

    #[cfg(feature = "full")]
    pub fn parse_items(input: &str) -> Result<Vec<Item>, String> {
        unwrap("items", item::parsing::items, input)
    }

    #[cfg(feature = "full")]
    pub fn parse_expr(input: &str) -> Result<Expr, String> {
        unwrap("expression", expr::parsing::expr, input)
    }

    pub fn parse_type(input: &str) -> Result<Ty, String> {
        unwrap("type", ty::parsing::ty, input)
    }

    pub fn parse_path(input: &str) -> Result<Path, String> {
        unwrap("path", ty::parsing::path, input)
    }

    pub fn parse_where_clause(input: &str) -> Result<WhereClause, String> {
        unwrap("where clause", generics::parsing::where_clause, input)
    }

    #[cfg(feature = "full")]
    pub fn parse_token_trees(input: &str) -> Result<Vec<TokenTree>, String> {
        unwrap("token trees", mac::parsing::token_trees, input)
    }

    fn unwrap<T>(name: &'static str,
                 f: fn(&str) -> IResult<&str, T>,
                 input: &str)
                 -> Result<T, String> {
        match f(input) {
            IResult::Done(mut rest, t) => {
                rest = space::skip_whitespace(rest);
                if rest.is_empty() {
                    Ok(t)
                } else if rest.len() == input.len() {
                    // parsed nothing
                    Err(format!("failed to parse {}: {:?}", name, rest))
                } else {
                    Err(format!("failed to parse tokens after {}: {:?}", name, rest))
                }
            }
            IResult::Error => Err(format!("failed to parse {}: {:?}", name, input)),
        }
    }
}
<commit_msg>Publically expose constant::Other and expr::FieldValue<commit_after>#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]

#[cfg(feature = "printing")]
#[macro_use]
extern crate quote;

#[cfg(feature = "pretty")]
extern crate syntex_syntax as syntax;

#[cfg(feature = "parsing")]
extern crate unicode_xid;

#[cfg(feature = "parsing")]
#[macro_use]
mod nom;

#[cfg(feature = "parsing")]
#[macro_use]
mod helper;

#[cfg(feature = "parsing")]
mod escape;

mod attr;
pub use attr::{Attribute, AttrStyle, MetaItem, NestedMetaItem};

mod constant;
pub use constant::ConstExpr;

mod data;
pub use data::{Field, Variant, VariantData, Visibility};

#[cfg(feature = "full")]
mod expr;
#[cfg(feature = "full")]
pub use expr::{Arm, BindingMode, Block, BlockCheckMode, CaptureBy, Expr, ExprKind, FieldPat,
               FieldValue, Local, MacStmtStyle, Pat, RangeLimits, Stmt};

mod generics;
pub use generics::{Generics, Lifetime, LifetimeDef, TraitBoundModifier, TyParam, TyParamBound,
                   WhereBoundPredicate, WhereClause, WherePredicate, WhereRegionPredicate};
#[cfg(feature = "printing")]
pub use generics::{ImplGenerics, TyGenerics};

#[cfg(feature = "full")]
mod krate;
#[cfg(feature = "full")]
pub use krate::Crate;

mod ident;
pub use ident::Ident;

#[cfg(feature = "full")]
mod item;
#[cfg(feature = "full")]
pub use item::{Constness, Defaultness, FnArg, FnDecl, ForeignItemKind, ForeignItem, ForeignMod,
               ImplItem, ImplItemKind, ImplPolarity, Item, ItemKind, MethodSig, PathListItem,
               TraitItem, TraitItemKind, ViewPath};

mod lit;
pub use lit::{FloatTy, IntTy, Lit, StrStyle};

#[cfg(feature = "full")]
mod mac;
#[cfg(feature = "full")]
pub use mac::{BinOpToken, DelimToken, Delimited, Mac, Token, TokenTree};

mod macro_input;
pub use macro_input::{Body, MacroInput};

mod op;
pub use op::{BinOp, UnOp};

#[cfg(feature = "expand")]
mod registry;
#[cfg(feature = "expand")]
pub use registry::{CustomDerive, Expanded, Registry};

#[cfg(feature = "parsing")]
mod space;

mod ty;
pub use ty::{Abi, AngleBracketedParameterData, BareFnArg, BareFnTy, FunctionRetTy, MutTy,
             Mutability, ParenthesizedParameterData, Path, PathParameters, PathSegment,
             PolyTraitRef, QSelf, Ty, TypeBinding, Unsafety};

#[cfg(feature = "aster")]
pub mod aster;

#[cfg(feature = "visit")]
pub mod visit;

#[cfg(feature = "parsing")]
pub use parsing::*;

#[cfg(feature = "parsing")]
mod parsing {
    use super::*;
    use {generics, macro_input, space, ty};
    use nom::IResult;

    #[cfg(feature = "full")]
    use {expr, item, krate, mac};

    pub fn parse_macro_input(input: &str) -> Result<MacroInput, String> {
        unwrap("macro input", macro_input::parsing::macro_input, input)
    }

    #[cfg(feature = "full")]
    pub fn parse_crate(input: &str) -> Result<Crate, String> {
        unwrap("crate", krate::parsing::krate, input)
    }

    #[cfg(feature = "full")]
    pub fn parse_item(input: &str) -> Result<Item, String> {
        unwrap("item", item::parsing::item, input)
    }

    #[cfg(feature = "full")]
    pub fn parse_items(input: &str) -> Result<Vec<Item>, String> {
        unwrap("items", item::parsing::items, input)
    }

    #[cfg(feature = "full")]
    pub fn parse_expr(input: &str) -> Result<Expr, String> {
        unwrap("expression", expr::parsing::expr, input)
    }

    pub fn parse_type(input: &str) -> Result<Ty, String> {
        unwrap("type", ty::parsing::ty, input)
    }

    pub fn parse_path(input: &str) -> Result<Path, String> {
        unwrap("path", ty::parsing::path, input)
    }

    pub fn parse_where_clause(input: &str) -> Result<WhereClause, String> {
        unwrap("where clause", generics::parsing::where_clause, input)
    }

    #[cfg(feature = "full")]
    pub fn parse_token_trees(input: &str) -> Result<Vec<TokenTree>, String> {
        unwrap("token trees", mac::parsing::token_trees, input)
    }

    fn unwrap<T>(name: &'static str,
                 f: fn(&str) -> IResult<&str, T>,
                 input: &str)
                 -> Result<T, String> {
        match f(input) {
            IResult::Done(mut rest, t) => {
                rest = space::skip_whitespace(rest);
                if rest.is_empty() {
                    Ok(t)
                } else if rest.len() == input.len() {
                    // parsed nothing
                    Err(format!("failed to parse {}: {:?}", name, rest))
                } else {
                    Err(format!("failed to parse tokens after {}: {:?}", name, rest))
                }
            }
            IResult::Error => Err(format!("failed to parse {}: {:?}", name, input)),
        }
    }
}
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! sorted-collections-rs is a library providing useful extension traits and convenience
//! methods for ordered collections in Rust.

#![feature(collections)]

#![cfg_attr(test, feature(test))] #[cfg(test)] extern crate test;

pub use sortedmap::SortedMapExt;
pub use sortedset::SortedSetExt;

pub mod sortedmap;
pub mod sortedset;
<commit_msg>Update to latest Rust<commit_after>// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! sorted-collections-rs is a library providing useful extension traits and convenience
//! methods for ordered collections in Rust.

#![feature(collections, core)]

#![cfg_attr(test, feature(test))] #[cfg(test)] extern crate test;

pub use sortedmap::SortedMapExt;
pub use sortedset::SortedSetExt;

pub mod sortedmap;
pub mod sortedset;
<|endoftext|>


<commit_before>//! This crate is a Rust port of Google's high-performance [SwissTable] hash
//! map, adapted to make it a drop-in replacement for Rust's standard `HashMap`
//! and `HashSet` types.
//!
//! The original C++ version of [SwissTable] can be found [here], and this
//! [CppCon talk] gives an overview of how the algorithm works.
//!
//! [SwissTable]: https://abseil.io/blog/20180927-swisstables
//! [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h
//! [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4

#![no_std]
#![cfg_attr(
    feature = "nightly",
    feature(
        test,
        core_intrinsics,
        dropck_eyepatch,
        min_specialization,
        extend_one,
        allocator_api,
        slice_ptr_get,
        nonnull_slice_from_raw_parts,
        maybe_uninit_array_assume_init
    )
)]
#![allow(
    clippy::doc_markdown,
    clippy::module_name_repetitions,
    clippy::must_use_candidate,
    clippy::option_if_let_else,
    clippy::redundant_else
)]
#![warn(missing_docs)]
#![warn(rust_2018_idioms)]

#[cfg(test)]
#[macro_use]
extern crate std;

#[cfg_attr(test, macro_use)]
extern crate alloc;

#[cfg(feature = "nightly")]
#[cfg(doctest)]
doc_comment::doctest!("../README.md");

#[macro_use]
mod macros;

#[cfg(feature = "raw")]
/// Experimental and unsafe `RawTable` API. This module is only available if the
/// `raw` feature is enabled.
pub mod raw {
    // The RawTable API is still experimental and is not properly documented yet.
    #[allow(missing_docs)]
    #[path = "mod.rs"]
    mod inner;
    pub use inner::*;

    #[cfg(feature = "rayon")]
    /// [rayon]-based parallel iterator types for hash maps.
    /// You will rarely need to interact with it directly unless you have need
    /// to name one of the iterator types.
    ///
    /// [rayon]: https://docs.rs/rayon/1.0/rayon
    pub mod rayon {
        pub use crate::external_trait_impls::rayon::raw::*;
    }
}
#[cfg(not(feature = "raw"))]
mod raw;

mod external_trait_impls;
mod map;
#[cfg(feature = "rustc-internal-api")]
mod rustc_entry;
mod scopeguard;
mod set;

pub mod hash_map {
    //! A hash map implemented with quadratic probing and SIMD lookup.
    pub use crate::map::*;

    #[cfg(feature = "rustc-internal-api")]
    pub use crate::rustc_entry::*;

    #[cfg(feature = "rayon")]
    /// [rayon]-based parallel iterator types for hash maps.
    /// You will rarely need to interact with it directly unless you have need
    /// to name one of the iterator types.
    ///
    /// [rayon]: https://docs.rs/rayon/1.0/rayon
    pub mod rayon {
        pub use crate::external_trait_impls::rayon::map::*;
    }
}
pub mod hash_set {
    //! A hash set implemented as a `HashMap` where the value is `()`.
    pub use crate::set::*;

    #[cfg(feature = "rayon")]
    /// [rayon]-based parallel iterator types for hash sets.
    /// You will rarely need to interact with it directly unless you have need
    /// to name one of the iterator types.
    ///
    /// [rayon]: https://docs.rs/rayon/1.0/rayon
    pub mod rayon {
        pub use crate::external_trait_impls::rayon::set::*;
    }
}

pub use crate::map::HashMap;
pub use crate::set::HashSet;

/// The error type for `try_reserve` methods.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum TryReserveError {
    /// Error due to the computed capacity exceeding the collection's maximum
    /// (usually `isize::MAX` bytes).
    CapacityOverflow,

    /// The memory allocator returned an error
    AllocError {
        /// The layout of the allocation request that failed.
        layout: alloc::alloc::Layout,
    },
}

/// The error type for [`RawTable::get_each_mut`](crate::raw::RawTable::get_each_mut),
/// [`HashMap::get_each_mut`], and [`HashMap::get_each_key_value_mut`].
#[cfg(feature = "nightly")]
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum UnavailableMutError {
    /// The requested entry is not present in the table.
    Absent,
    /// The requested entry is present, but a mutable reference to it was already created and
    /// returned from this call to `get_each_mut` or `get_each_key_value_mut`.
    ///
    /// Includes the index of the existing mutable reference in the returned array.
    Duplicate(usize),
}

/// Wrapper around `Bump` which allows it to be used as an allocator for
/// `HashMap`, `HashSet` and `RawTable`.
///
/// `Bump` can be used directly without this wrapper on nightly if you enable
/// the `allocator-api` feature of the `bumpalo` crate.
#[cfg(feature = "bumpalo")]
#[derive(Clone, Copy, Debug)]
pub struct BumpWrapper<'a>(&'a bumpalo::Bump);

#[cfg(feature = "bumpalo")]
#[test]
fn test_bumpalo() {
    use bumpalo::Bump;
    let bump = Bump::new();
    let mut map = HashMap::new_in(BumpWrapper(&bump));
    map.insert(0, 1);
}
<commit_msg>Allow clippy::manual_map<commit_after>//! This crate is a Rust port of Google's high-performance [SwissTable] hash
//! map, adapted to make it a drop-in replacement for Rust's standard `HashMap`
//! and `HashSet` types.
//!
//! The original C++ version of [SwissTable] can be found [here], and this
//! [CppCon talk] gives an overview of how the algorithm works.
//!
//! [SwissTable]: https://abseil.io/blog/20180927-swisstables
//! [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h
//! [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4

#![no_std]
#![cfg_attr(
    feature = "nightly",
    feature(
        test,
        core_intrinsics,
        dropck_eyepatch,
        min_specialization,
        extend_one,
        allocator_api,
        slice_ptr_get,
        nonnull_slice_from_raw_parts,
        maybe_uninit_array_assume_init
    )
)]
#![allow(
    clippy::doc_markdown,
    clippy::module_name_repetitions,
    clippy::must_use_candidate,
    clippy::option_if_let_else,
    clippy::redundant_else,
    clippy::manual_map
)]
#![warn(missing_docs)]
#![warn(rust_2018_idioms)]

#[cfg(test)]
#[macro_use]
extern crate std;

#[cfg_attr(test, macro_use)]
extern crate alloc;

#[cfg(feature = "nightly")]
#[cfg(doctest)]
doc_comment::doctest!("../README.md");

#[macro_use]
mod macros;

#[cfg(feature = "raw")]
/// Experimental and unsafe `RawTable` API. This module is only available if the
/// `raw` feature is enabled.
pub mod raw {
    // The RawTable API is still experimental and is not properly documented yet.
    #[allow(missing_docs)]
    #[path = "mod.rs"]
    mod inner;
    pub use inner::*;

    #[cfg(feature = "rayon")]
    /// [rayon]-based parallel iterator types for hash maps.
    /// You will rarely need to interact with it directly unless you have need
    /// to name one of the iterator types.
    ///
    /// [rayon]: https://docs.rs/rayon/1.0/rayon
    pub mod rayon {
        pub use crate::external_trait_impls::rayon::raw::*;
    }
}
#[cfg(not(feature = "raw"))]
mod raw;

mod external_trait_impls;
mod map;
#[cfg(feature = "rustc-internal-api")]
mod rustc_entry;
mod scopeguard;
mod set;

pub mod hash_map {
    //! A hash map implemented with quadratic probing and SIMD lookup.
    pub use crate::map::*;

    #[cfg(feature = "rustc-internal-api")]
    pub use crate::rustc_entry::*;

    #[cfg(feature = "rayon")]
    /// [rayon]-based parallel iterator types for hash maps.
    /// You will rarely need to interact with it directly unless you have need
    /// to name one of the iterator types.
    ///
    /// [rayon]: https://docs.rs/rayon/1.0/rayon
    pub mod rayon {
        pub use crate::external_trait_impls::rayon::map::*;
    }
}
pub mod hash_set {
    //! A hash set implemented as a `HashMap` where the value is `()`.
    pub use crate::set::*;

    #[cfg(feature = "rayon")]
    /// [rayon]-based parallel iterator types for hash sets.
    /// You will rarely need to interact with it directly unless you have need
    /// to name one of the iterator types.
    ///
    /// [rayon]: https://docs.rs/rayon/1.0/rayon
    pub mod rayon {
        pub use crate::external_trait_impls::rayon::set::*;
    }
}

pub use crate::map::HashMap;
pub use crate::set::HashSet;

/// The error type for `try_reserve` methods.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum TryReserveError {
    /// Error due to the computed capacity exceeding the collection's maximum
    /// (usually `isize::MAX` bytes).
    CapacityOverflow,

    /// The memory allocator returned an error
    AllocError {
        /// The layout of the allocation request that failed.
        layout: alloc::alloc::Layout,
    },
}

/// The error type for [`RawTable::get_each_mut`](crate::raw::RawTable::get_each_mut),
/// [`HashMap::get_each_mut`], and [`HashMap::get_each_key_value_mut`].
#[cfg(feature = "nightly")]
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum UnavailableMutError {
    /// The requested entry is not present in the table.
    Absent,
    /// The requested entry is present, but a mutable reference to it was already created and
    /// returned from this call to `get_each_mut` or `get_each_key_value_mut`.
    ///
    /// Includes the index of the existing mutable reference in the returned array.
    Duplicate(usize),
}

/// Wrapper around `Bump` which allows it to be used as an allocator for
/// `HashMap`, `HashSet` and `RawTable`.
///
/// `Bump` can be used directly without this wrapper on nightly if you enable
/// the `allocator-api` feature of the `bumpalo` crate.
#[cfg(feature = "bumpalo")]
#[derive(Clone, Copy, Debug)]
pub struct BumpWrapper<'a>(&'a bumpalo::Bump);

#[cfg(feature = "bumpalo")]
#[test]
fn test_bumpalo() {
    use bumpalo::Bump;
    let bump = Bump::new();
    let mut map = HashMap::new_in(BumpWrapper(&bump));
    map.insert(0, 1);
}
<|endoftext|>


<commit_before>//! A basic ZipReader/Writer crate

#![feature(unsafe_destructor)]
#![warn(missing_docs)]

#![feature(core, collections, io, std_misc)]

extern crate time;
extern crate flate2;
extern crate bzip2;

pub use reader::ZipReader;
pub use writer::ZipWriter;
pub use compression::CompressionMethod;
pub use types::ZipFile;

mod util;
mod spec;
mod reader_spec;
mod writer_spec;
mod crc32;
mod reader;
mod types;
pub mod compression;
mod writer;
mod cp437;
pub mod result;
<commit_msg>Remove all old_io warnings<commit_after>//! A basic ZipReader/Writer crate

#![feature(unsafe_destructor)]
#![warn(missing_docs)]

#![feature(core, collections, old_io, std_misc)]

extern crate time;
extern crate flate2;
extern crate bzip2;

pub use reader::ZipReader;
pub use writer::ZipWriter;
pub use compression::CompressionMethod;
pub use types::ZipFile;

mod util;
mod spec;
mod reader_spec;
mod writer_spec;
mod crc32;
mod reader;
mod types;
pub mod compression;
mod writer;
mod cp437;
pub mod result;
<|endoftext|>


<commit_before>use std::io;
use std::io::prelude::*;
use std::io::{Error, ErrorKind};

pub trait Endec {
    type T;

    fn encoded_len(value: &Self::T) -> usize;

    fn encode(value: &Self::T, dst: &mut Write) -> io::Result<usize>;
    fn decode(src: &mut Read) -> io::Result<Self::T>;
}

impl Endec for u16 {
    type T = u16;

    fn encoded_len(value: &Self::T) -> usize {
        2
    }

    fn encode(value: &Self::T, dst: &mut Write) -> io::Result<usize> {
        let mut buf = [0u8; 2];
        buf[0] = (value >> 8 & 0xffu8 as u16) as u8;
        buf[1] = (value & 0xffu8 as u16) as u8;

        assert_eq!(dst.write(&buf).is_ok(), true);
        Ok(2)
    }

    fn decode(src: &mut Read) -> io::Result<Self::T> {
        let mut buf = [0u8; 2];
        assert_eq!(src.read(&mut buf).is_ok(), true);
        Ok(((buf[0] as u16) << 8 ) | (buf[1] as u16))
    }
}

macro_rules! packets {
    ($($id:expr => $name:ident { $($fname:ident: $fty:ty),* })+) => {
        #[derive(Debug)]
        enum Protocol {
            $(
                $name { $($fname:$fty),* }
             ),+
        }

        impl Endec for Protocol {
            type T = Protocol ;

            fn encoded_len(value: &Self::T) -> usize {
                10
            }

            fn encode(value: &Self::T, dst: &mut Write) -> io::Result<usize> {
                let mut len: usize = 0;

                match value { $(
                    &Protocol::$name { $($fname),* } => {$(
                        //TODO: try! is not the best thing here
                        len += try!(<$fty as Endec>::encode(&$fname, dst));
                    )*}
                )+}

                Ok(len)
            }

            fn decode(src: &mut Read) -> io::Result<Self::T> {
                let id = 0;

                match id {
                    $(
                        $id => Ok(Protocol::$name {
                                    $(
                                        $fname:try!(<$fty as Endec>::decode(src))
                                    ),*
                                }),
                    )+
                        _ => Err(Error::new(ErrorKind::Other, "oh no!"))
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io;
    use std::io::prelude::*;
    use std::io::{Error, ErrorKind};

    packets! {
        0 => Message { a: u16, b: u16 }
        1 => Msg { b: u16 }
    }

    #[test]
    fn test_main() {
        let x:Protocol = Protocol::Message { a: 10, b: 15 };
        let mut buf:Vec<u8> = Vec::new();
        Protocol::encode(&x, &mut buf);
        println!("{:?}", buf);
    }

}
<commit_msg>macro now generates proper trait implementation<commit_after>use std::io;
use std::io::prelude::*;
use std::io::{Error, ErrorKind};

pub trait Endec {
    type T;

    fn encoded_len(value: &Self::T) -> usize;

    fn encode(value: &Self::T, dst: &mut Write) -> io::Result<usize>;
    fn decode(src: &mut Read) -> io::Result<Self::T>;
}

impl Endec for u16 {
    type T = u16;

    fn encoded_len(value: &Self::T) -> usize {
        2
    }

    fn encode(value: &Self::T, dst: &mut Write) -> io::Result<usize> {
        let mut buf = [0u8; 2];
        buf[0] = (value >> 8 & 0xffu8 as u16) as u8;
        buf[1] = (value & 0xffu8 as u16) as u8;

        assert_eq!(dst.write(&buf).is_ok(), true);
        Ok(2)
    }

    fn decode(src: &mut Read) -> io::Result<Self::T> {
        let mut buf = [0u8; 2];
        assert_eq!(src.read(&mut buf).is_ok(), true);
        Ok(((buf[0] as u16) << 8 ) | (buf[1] as u16))
    }
}

macro_rules! packets {
    ($($id:expr => $name:ident { $($fname:ident: $fty:ty),* })+) => {
        #[derive(Debug)]
        enum Protocol {
            $(
                $name { $($fname:$fty),* }
             ),+
        }

        impl Endec for Protocol {
            type T = Protocol ;

            fn encoded_len(value: &Self::T) -> usize {
                let mut len: usize = 0;

                match value { $(
                    &Protocol::$name { $($fname),* } => {$(
                        //TODO: try! is not the best thing here
                        len += <$fty as Endec>::encoded_len(&$fname);
                    )*}
                )+}

                len
            }

            fn encode(value: &Self::T, dst: &mut Write) -> io::Result<usize> {
                let mut len: usize = 0;

                match value { $(
                    &Protocol::$name { $($fname),* } => {$(
                        //TODO: try! is not the best thing here
                        len += try!(<$fty as Endec>::encode(&$fname, dst));
                    )*}
                )+}

                Ok(len)
            }

            fn decode(src: &mut Read) -> io::Result<Self::T> {
                let id = 0;

                match id {
                    $(
                        $id => Ok(Protocol::$name {
                                    $(
                                        $fname:try!(<$fty as Endec>::decode(src))
                                    ),*
                                }),
                    )+
                        _ => Err(Error::new(ErrorKind::Other, "oh no!"))
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io;
    use std::io::prelude::*;
    use std::io::{Error, ErrorKind};

    packets! {
        0 => Message { a: u16, b: u16 }
        1 => Msg { b: u16 }
    }

    #[test]
    fn test_main() {
        let x:Protocol = Protocol::Message { a: 10, b: 15 };
        let mut buf:Vec<u8> = Vec::new();
        Protocol::encode(&x, &mut buf);
        println!("{:?}", buf);
        assert!(Protocol::encoded_len(&x) == 4);
    }

}
<|endoftext|>


<commit_before>//extern crate libc;
//
//use libc::{c_void, c_int, c_char, c_ulong, c_long, c_uint, c_uchar, size_t};
//use std::mem;
//use std::ptr;

#[link(name = "isl")]
extern {
    fn isl_ctx_alloc() -> Box<Ctx>;
}

// safe wrapper
fn getCtx() -> Box<Ctx>  {
    unsafe { isl_ctx_alloc() }
}

//isl_ctx *ctx = isl_ctx_alloc();

#[repr(C)]
#[derive(Clone, Copy)]
// TODO align with isl/include/isl/isl_ctx_private.h
struct Ctx {
    ref_: i32,
}

#[test]
fn it_works() {
    // see https://github.com/rust-lang/rust/issues/20204
    // rust je_arena_dalloc_bin_locked
    //let ctx = getCtx();
    unsafe {
        let ctx = isl_ctx_alloc();
    }
}
<commit_msg>use raw pointers instead of boxed ones.<commit_after>//extern crate libc;
//
//use libc::{c_void, c_int, c_char, c_ulong, c_long, c_uint, c_uchar, size_t};
//use std::mem;
//use std::ptr;

#[link(name = "isl")]
extern {
    //fn isl_ctx_alloc() -> Box<Ctx>;
    fn isl_ctx_alloc() -> *mut i64;
}

// safe wrapper
//fn getCtx() -> Box<Ctx>  {
fn getCtx() -> *mut i64  {
    unsafe { isl_ctx_alloc() }
}

//isl_ctx *ctx = isl_ctx_alloc();

#[repr(C)]
#[derive(Clone, Copy)]
// TODO align with isl/include/isl/isl_ctx_private.h
struct Ctx {
    ref_: i32,
}

#[test]
fn it_works() {
    // see https://github.com/rust-lang/rust/issues/20204
    // used to have with boxed values: rust je_arena_dalloc_bin_locked
    let ctx = getCtx();
    unsafe {
      assert!(*ctx != 0);
    }
}
<|endoftext|>


<commit_before>//! # Libinput bindings for rust
//!
//! These bindings closely follow libinput's concepts and it's original API.
//! Please refer to the [libinput documentation](https://wayland.freedesktop.org/libinput/doc/latest/)
//! to understand the general structure and concepts.
//!
//! ## Differences to the C-Library:
//!
//! - Refcounting does not need to be done manually. Just call `clone` when you need an additional reference.
//! - Libinput logging cannot (currently) not be customized.
//!
//! ## Userdata handling
//!
//! Multiple types in the libinput library allow to attach a pointer of an arbitrary type, so called `userdata`.
//! Using this data is unsafe as there is no way to find out what type is stored in the libinput struct.
//! Additionally multiple references to the same libinput object may exist and userdata may be shared mutably.
//!
//! This is why using and setting userdata is an unsafe operation (except when creating an object).
//!
//! If you heavily rely on userdata, you should always stored them wrapped in a `Mutex` and use the same
//! type for every userdata access to further simplify usage.
//!
//! You need to be especially cautious when initializing libinput types from raw pointers, you obtained
//! from other libraries which may set their own userdata. If accessing their userdata make sure no shared
//! mutable access may happen and don't store something else instead, if the library does not explicitly
//! allow this.
//!
//! Generally usage of this api is error-prone and discouraged if not needed.
//!
//! ## Getting started
//!
//! To get started check out the [`Libinput` struct](./struct.Libinput.html).
//!

#![deny(missing_docs)]
#![cfg_attr(feature="cargo-clippy", deny(clippy))]
#![cfg_attr(feature="cargo-clippy", allow(doc_markdown))]

extern crate input_sys;
extern crate libc;

#[macro_use]
extern crate bitflags;

use std::{mem, ptr};

/// Unsafe c-api.
pub mod ffi {
    pub use input_sys::*;
}

/// Trait for types that allow to optain the underlying raw libinput pointer.
pub trait AsRaw<T> {
    /// Receive a raw pointer representing this type.
    fn as_raw(&self) -> *const T;
    #[doc(hidden)]
    fn as_raw_mut(&self) -> *mut T {
        self.as_raw() as *mut _
    }
}

/// Trait for types that allow to be initialized from a raw pointer
pub trait FromRaw<T> {
    /// Create a new instance of this type from a raw pointer.
    ///
    /// ## Warning
    ///
    /// If you make use of [`Userdata`](./trait.Userdata.html) make sure you use the correct types
    /// to allow receiving the set userdata. When dealing with raw pointers initialized by other
    /// libraries this must be done extra carefully to select a correct representation.
    ///
    /// If unsure using `()` is always a safe option..
    ///
    /// ## Unsafety
    ///
    /// If the pointer is pointing to a different struct, invalid memory or `NULL` the returned
    /// struct may panic on use or cause other undefined behavior.
    ///
    unsafe fn from_raw(*mut T) -> Self;
}

/// Trait to deal with userdata attached to this struct.
pub trait Userdata {
    /// Receive a reference to the attached userdata, if one exists.
    ///
    /// ## Unsafety
    ///
    /// Receiving userdata is unsafe as multiple references to the same underlying libinput struct
    /// may exist. As such any reference may become invalid if changed using `set_userdata`.
    ///
    unsafe fn userdata<T: 'static>(&self) -> Option<&T> {
        self.userdata_raw().as_ref()
    }

    /// Receive a mutable reference to the attached userdata, if one exists.
    ///
    /// ## Unsafety
    ///
    /// Receiving userdata is unsafe as multiple references to the same underlying libinput struct
    /// may exist. As such any reference may become invalid if changed using `set_userdata`.
    ///
    /// Additionally multiple mutable references may be created through the existance of multiple
    /// structs using the same libinput reference. If you have control over the userdata make sure
    /// to store `Mutex` to be on the safe side.
    ///
    unsafe fn userdata_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.userdata_raw().as_mut()
    }

    /// Set userdata and receive the currently set userdata
    ///
    /// Sets new userdata or nothing in place of any existing one and returns the currently set
    /// userdata if one exists.
    ///
    /// ## Unsafety
    ///
    /// Multiple references to the same underlying libinput struct may exist. As such this function
    /// allows for shared mutable access, which is unsafe. Also this means this function
    /// might invalidate references to the currently set userdata, once dropped.
    ///
    /// Use a `Mutex` when storing new userdata to mitiage some of these problems.
    ///
    /// ## Note
    ///
    /// Stored userdata is dropped correctly, if the last reference is hold by rust and goes out of scope normally.
    unsafe fn set_userdata<T: 'static, U: 'static>(&mut self, new: Option<T>) -> Option<U> {
        let old = {
            let ptr = self.userdata_raw();
            if !ptr.is_null() {
                Some(Box::from_raw(ptr as *mut U))
            } else {
                None
            }
        };
        let mut boxed = Box::new(new);
        self.set_userdata_raw(match (*boxed).as_mut() {
                                  Some(value) => value as *mut T,
                                  None => ptr::null_mut(),
                              });
        mem::forget(boxed);
        old.map(|x| *x)
    }

    #[doc(hidden)]
    unsafe fn userdata_raw<T: 'static>(&self) -> *mut T;
    #[doc(hidden)]
    unsafe fn set_userdata_raw<T: 'static>(&self, ptr: *mut T);
}

macro_rules! ffi_ref_struct {
    ($(#[$attr:meta])* struct $struct_name:ident, $ffi_name:path, $ref_fn:path, $unref_fn:path, $get_userdata_fn:path, $set_userdata_fn:path) => (
        #[derive(Eq)]
        $(#[$attr])*
        pub struct $struct_name
        {
            ffi: *mut $ffi_name,
        }

        impl ::std::fmt::Debug for $struct_name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                write!(f, "$struct_name @{:p}", self.as_raw())
            }
        }

        impl FromRaw<$ffi_name> for $struct_name
        {
            unsafe fn from_raw(ffi: *mut $ffi_name) -> Self {
                $struct_name {
                    ffi: $ref_fn(ffi),
                }
            }
        }

        impl AsRaw<$ffi_name> for $struct_name
        {
            fn as_raw(&self) -> *const $ffi_name {
                self.ffi as *const _
            }
        }

        impl Userdata for $struct_name {
            unsafe fn userdata_raw<T: 'static>(&self) -> *mut T {
                $get_userdata_fn(self.as_raw_mut()) as *mut T
            }
            unsafe fn set_userdata_raw<T: 'static>(&self, ptr: *mut T) {
                $set_userdata_fn(self.as_raw_mut(), ptr as *mut libc::c_void);
            }
        }

        impl Clone for $struct_name {
            fn clone(&self) -> Self {
                unsafe { $struct_name::from_raw(self.as_raw_mut()) }
            }
        }

        impl Drop for $struct_name
        {
            fn drop(&mut self) {
                unsafe {
                    let userdata_ref = $get_userdata_fn(self.as_raw_mut());
                    if $unref_fn(self.ffi).is_null() {
                        let _ = Box::from_raw(userdata_ref);
                    }
                }
            }
        }

        impl PartialEq for $struct_name {
            fn eq(&self, other: &Self) -> bool {
                self.as_raw() == other.as_raw()
            }
        }

        impl ::std::hash::Hash for $struct_name {
            fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
                self.as_raw().hash(state);
            }
        }
    )
}

macro_rules! ffi_func {
    ($(#[$attr:meta])* fn $name:ident, $ffi_fn:path, bool) => (
        $(#[$attr])*
        fn $name(&self) -> bool {
            unsafe { $ffi_fn(self.as_raw_mut()) != 0 }
        }
    );
    ($(#[$attr:meta])* pub fn $name:ident, $ffi_fn:path, bool) => (
        $(#[$attr])*
        pub fn $name(&self) -> bool {
            unsafe { $ffi_fn(self.as_raw_mut()) != 0 }
        }
    );
    ($(#[$attr:meta])* fn $name:ident, $ffi_fn:path, $return_type:ty) => (
        $(#[$attr])*
        fn $name(&self) -> $return_type {
            unsafe { $ffi_fn(self.as_raw_mut()) as $return_type }
        }
    );
    ($(#[$attr:meta])* pub fn $name:ident, $ffi_fn:path, $return_type:ty) => (
        $(#[$attr])*
        pub fn $name(&self) -> $return_type {
            unsafe { $ffi_fn(self.as_raw_mut()) as $return_type }
        }
    );
}

mod context;
mod device;
pub mod event;
mod seat;

pub use context::*;
pub use device::*;
pub use event::Event;
pub use seat::*;
<commit_msg>Don't try to free null userdata.<commit_after>//! # Libinput bindings for rust
//!
//! These bindings closely follow libinput's concepts and it's original API.
//! Please refer to the [libinput documentation](https://wayland.freedesktop.org/libinput/doc/latest/)
//! to understand the general structure and concepts.
//!
//! ## Differences to the C-Library:
//!
//! - Refcounting does not need to be done manually. Just call `clone` when you need an additional reference.
//! - Libinput logging cannot (currently) not be customized.
//!
//! ## Userdata handling
//!
//! Multiple types in the libinput library allow to attach a pointer of an arbitrary type, so called `userdata`.
//! Using this data is unsafe as there is no way to find out what type is stored in the libinput struct.
//! Additionally multiple references to the same libinput object may exist and userdata may be shared mutably.
//!
//! This is why using and setting userdata is an unsafe operation (except when creating an object).
//!
//! If you heavily rely on userdata, you should always stored them wrapped in a `Mutex` and use the same
//! type for every userdata access to further simplify usage.
//!
//! You need to be especially cautious when initializing libinput types from raw pointers, you obtained
//! from other libraries which may set their own userdata. If accessing their userdata make sure no shared
//! mutable access may happen and don't store something else instead, if the library does not explicitly
//! allow this.
//!
//! Generally usage of this api is error-prone and discouraged if not needed.
//!
//! ## Getting started
//!
//! To get started check out the [`Libinput` struct](./struct.Libinput.html).
//!

#![deny(missing_docs)]
#![cfg_attr(feature="cargo-clippy", deny(clippy))]
#![cfg_attr(feature="cargo-clippy", allow(doc_markdown))]

extern crate input_sys;
extern crate libc;

#[macro_use]
extern crate bitflags;

use std::{mem, ptr};

/// Unsafe c-api.
pub mod ffi {
    pub use input_sys::*;
}

/// Trait for types that allow to optain the underlying raw libinput pointer.
pub trait AsRaw<T> {
    /// Receive a raw pointer representing this type.
    fn as_raw(&self) -> *const T;
    #[doc(hidden)]
    fn as_raw_mut(&self) -> *mut T {
        self.as_raw() as *mut _
    }
}

/// Trait for types that allow to be initialized from a raw pointer
pub trait FromRaw<T> {
    /// Create a new instance of this type from a raw pointer.
    ///
    /// ## Warning
    ///
    /// If you make use of [`Userdata`](./trait.Userdata.html) make sure you use the correct types
    /// to allow receiving the set userdata. When dealing with raw pointers initialized by other
    /// libraries this must be done extra carefully to select a correct representation.
    ///
    /// If unsure using `()` is always a safe option..
    ///
    /// ## Unsafety
    ///
    /// If the pointer is pointing to a different struct, invalid memory or `NULL` the returned
    /// struct may panic on use or cause other undefined behavior.
    ///
    unsafe fn from_raw(*mut T) -> Self;
}

/// Trait to deal with userdata attached to this struct.
pub trait Userdata {
    /// Receive a reference to the attached userdata, if one exists.
    ///
    /// ## Unsafety
    ///
    /// Receiving userdata is unsafe as multiple references to the same underlying libinput struct
    /// may exist. As such any reference may become invalid if changed using `set_userdata`.
    ///
    unsafe fn userdata<T: 'static>(&self) -> Option<&T> {
        self.userdata_raw().as_ref()
    }

    /// Receive a mutable reference to the attached userdata, if one exists.
    ///
    /// ## Unsafety
    ///
    /// Receiving userdata is unsafe as multiple references to the same underlying libinput struct
    /// may exist. As such any reference may become invalid if changed using `set_userdata`.
    ///
    /// Additionally multiple mutable references may be created through the existance of multiple
    /// structs using the same libinput reference. If you have control over the userdata make sure
    /// to store `Mutex` to be on the safe side.
    ///
    unsafe fn userdata_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.userdata_raw().as_mut()
    }

    /// Set userdata and receive the currently set userdata
    ///
    /// Sets new userdata or nothing in place of any existing one and returns the currently set
    /// userdata if one exists.
    ///
    /// ## Unsafety
    ///
    /// Multiple references to the same underlying libinput struct may exist. As such this function
    /// allows for shared mutable access, which is unsafe. Also this means this function
    /// might invalidate references to the currently set userdata, once dropped.
    ///
    /// Use a `Mutex` when storing new userdata to mitiage some of these problems.
    ///
    /// ## Note
    ///
    /// Stored userdata is dropped correctly, if the last reference is hold by rust and goes out of scope normally.
    unsafe fn set_userdata<T: 'static, U: 'static>(&mut self, new: Option<T>) -> Option<U> {
        let old = {
            let ptr = self.userdata_raw();
            if !ptr.is_null() {
                Some(Box::from_raw(ptr as *mut U))
            } else {
                None
            }
        };
        let mut boxed = Box::new(new);
        self.set_userdata_raw(match (*boxed).as_mut() {
                                  Some(value) => value as *mut T,
                                  None => ptr::null_mut(),
                              });
        mem::forget(boxed);
        old.map(|x| *x)
    }

    #[doc(hidden)]
    unsafe fn userdata_raw<T: 'static>(&self) -> *mut T;
    #[doc(hidden)]
    unsafe fn set_userdata_raw<T: 'static>(&self, ptr: *mut T);
}

macro_rules! ffi_ref_struct {
    ($(#[$attr:meta])* struct $struct_name:ident, $ffi_name:path, $ref_fn:path, $unref_fn:path, $get_userdata_fn:path, $set_userdata_fn:path) => (
        #[derive(Eq)]
        $(#[$attr])*
        pub struct $struct_name
        {
            ffi: *mut $ffi_name,
        }

        impl ::std::fmt::Debug for $struct_name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                write!(f, "$struct_name @{:p}", self.as_raw())
            }
        }

        impl FromRaw<$ffi_name> for $struct_name
        {
            unsafe fn from_raw(ffi: *mut $ffi_name) -> Self {
                $struct_name {
                    ffi: $ref_fn(ffi),
                }
            }
        }

        impl AsRaw<$ffi_name> for $struct_name
        {
            fn as_raw(&self) -> *const $ffi_name {
                self.ffi as *const _
            }
        }

        impl Userdata for $struct_name {
            unsafe fn userdata_raw<T: 'static>(&self) -> *mut T {
                $get_userdata_fn(self.as_raw_mut()) as *mut T
            }
            unsafe fn set_userdata_raw<T: 'static>(&self, ptr: *mut T) {
                $set_userdata_fn(self.as_raw_mut(), ptr as *mut libc::c_void);
            }
        }

        impl Clone for $struct_name {
            fn clone(&self) -> Self {
                unsafe { $struct_name::from_raw(self.as_raw_mut()) }
            }
        }

        impl Drop for $struct_name
        {
            fn drop(&mut self) {
                unsafe {
                    let userdata_ref = $get_userdata_fn(self.as_raw_mut());
                    if $unref_fn(self.ffi).is_null() && !userdata_ref.is_null() {
                        let _ = Box::from_raw(userdata_ref);
                    }
                }
            }
        }

        impl PartialEq for $struct_name {
            fn eq(&self, other: &Self) -> bool {
                self.as_raw() == other.as_raw()
            }
        }

        impl ::std::hash::Hash for $struct_name {
            fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
                self.as_raw().hash(state);
            }
        }
    )
}

macro_rules! ffi_func {
    ($(#[$attr:meta])* fn $name:ident, $ffi_fn:path, bool) => (
        $(#[$attr])*
        fn $name(&self) -> bool {
            unsafe { $ffi_fn(self.as_raw_mut()) != 0 }
        }
    );
    ($(#[$attr:meta])* pub fn $name:ident, $ffi_fn:path, bool) => (
        $(#[$attr])*
        pub fn $name(&self) -> bool {
            unsafe { $ffi_fn(self.as_raw_mut()) != 0 }
        }
    );
    ($(#[$attr:meta])* fn $name:ident, $ffi_fn:path, $return_type:ty) => (
        $(#[$attr])*
        fn $name(&self) -> $return_type {
            unsafe { $ffi_fn(self.as_raw_mut()) as $return_type }
        }
    );
    ($(#[$attr:meta])* pub fn $name:ident, $ffi_fn:path, $return_type:ty) => (
        $(#[$attr])*
        pub fn $name(&self) -> $return_type {
            unsafe { $ffi_fn(self.as_raw_mut()) as $return_type }
        }
    );
}

mod context;
mod device;
pub mod event;
mod seat;

pub use context::*;
pub use device::*;
pub use event::Event;
pub use seat::*;
<|endoftext|>


<commit_before>#![deny(warnings)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![doc(html_root_url = "https://docs.rs/reqwest/0.7.3")]

//! # reqwest
//!
//! The `reqwest` crate provides a convenient, higher-level HTTP Client.
//!
//! It handles many of the things that most people just expect an HTTP client
//! to do for them.
//!
//! - Uses system-native TLS
//! - Plain bodies, JSON, urlencoded, multipart
//! - Customizable redirect policy
//! - Proxies
//! - (TODO: Cookies)
//!
//! The `reqwest::Client` is synchronous, making it a great fit for
//! applications that only require a few HTTP requests, and wish to handle
//! them synchronously.
//!
//! ## Making a GET request
//!
//! For a single request, you can use the [`get`][get] shortcut method.
//!
//! ```rust
//! use std::io::Read;
//! # use reqwest::{Error, Response};
//!
//! # fn run() -> Result<Response, Error> {
//! let mut resp = reqwest::get("https://www.rust-lang.org")?;
//! assert!(resp.status().is_success());
//!
//! let mut content = String::new();
//! resp.read_to_string(&mut content);
//! # Ok(resp)
//! # }
//! ```
//!
//! As you can see, reqwest's [`Response`][response] struct implements Rust's
//! `Read` trait, so many useful standard library and third party crates will
//! have convenience methods that take a `Response` anywhere `T: Read` is
//! acceptable.
//!
//! If you plan to perform multiple requests, it is best to create a [`Client`][client]
//! and reuse it, taking advantage of keep-alive connection pooling.
//!
//! ## Making POST requests (or setting request bodies)
//!
//! There are several ways you can set the body of a request. The basic one is
//! by using the `body()` method of a [`RequestBuilder`][builder]. This lets you set the
//! exact raw bytes of what the body should be. It accepts various types,
//! including `String`, `Vec<u8>`, and `File`. If you wish to pass a custom
//! Reader, you can use the `reqwest::Body::new()` constructor.
//!
//! ```rust
//! # use reqwest::Error;
//! #
//! # fn run() -> Result<(), Error> {
//! let client = reqwest::Client::new();
//! let res = client.post("http://httpbin.org/post")
//!     .body("the exact body that is sent")
//!     .send()?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Forms
//!
//! It's very common to want to send form data in a request body. This can be
//! done with any type that can be serialized into form data.
//!
//! This can be an array of tuples, or a `HashMap`, or a custom type that
//! implements [`Serialize`][serde].
//!
//! ```rust
//! # use reqwest::Error;
//! #
//! # fn run() -> Result<(), Error> {
//! // This will POST a body of `foo=bar&baz=quux`
//! let params = [("foo", "bar"), ("baz", "quux")];
//! let client = reqwest::Client::new();
//! let res = client.post("http://httpbin.org/post")
//!     .form(&params)
//!     .send()?;
//! # Ok(())
//! # }
//! ```
//!
//! ### JSON
//!
//! There is also a `json` method helper on the [`RequestBuilder`][builder] that works in
//! a similar fashion the `form` method. It can take any value that can be
//! serialized into JSON.
//!
//! ```rust
//! # use reqwest::Error;
//! # use std::collections::HashMap;
//! #
//! # fn run() -> Result<(), Error> {
//! // This will POST a body of `{"lang":"rust","body":"json"}`
//! let mut map = HashMap::new();
//! map.insert("lang", "rust");
//! map.insert("body", "json");
//!
//! let client = reqwest::Client::new();
//! let res = client.post("http://httpbin.org/post")
//!     .json(&map)
//!     .send()?;
//! # Ok(())
//! # }
//! ```
//!
//! [hyper]: http://hyper.rs
//! [client]: ./struct.Client.html
//! [response]: ./struct.Response.html
//! [get]: ./fn.get.html
//! [builder]: ./client/struct.RequestBuilder.html
//! [serde]: http://serde.rs

extern crate bytes;
#[macro_use]
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
#[macro_use]
extern crate log;
extern crate libflate;
extern crate mime_guess;
extern crate native_tls;
extern crate serde;
extern crate serde_json;
extern crate serde_urlencoded;
extern crate tokio_core;
extern crate tokio_io;
extern crate tokio_tls;
extern crate url;
extern crate uuid;

pub use hyper::header;
pub use hyper::mime;
pub use hyper::Method;
pub use hyper::StatusCode;
pub use url::Url;
pub use url::ParseError as UrlError;

pub use self::client::{Client, ClientBuilder};
pub use self::error::{Error, Result};
pub use self::body::Body;
pub use self::into_url::IntoUrl;
pub use self::proxy::Proxy;
pub use self::redirect::{RedirectAction, RedirectAttempt, RedirectPolicy};
pub use self::request::{Request, RequestBuilder};
pub use self::response::Response;
pub use self::tls::{Certificate, Identity};

// this module must be first because of the `try_` macro
#[macro_use]
mod error;

mod async_impl;
mod connect;
mod body;
mod client;
mod into_url;
mod multipart_;
mod proxy;
mod redirect;
mod request;
mod response;
mod tls;
mod wait;

pub mod multipart;

/// A set of unstable functionality.
///
/// This module is only available when the `unstable` [feature][] is enabled.
/// There is no backwards compatibility guarantee for any of the types within.
///
/// [feature]: http://doc.crates.io/specifying-dependencies.html#choosing-features
#[cfg(feature = "unstable")]
pub mod unstable {
    /// An 'async' implementation of the reqwest `Client`.
    ///
    /// Relies on the `futures` crate, which is unstable, hence this module
    /// is **unstable**.
    pub mod async {
        pub use ::async_impl::{
            Body,
            Chunk,
            Decoder,
            Client,
            ClientBuilder,
            Request,
            RequestBuilder,
            Response,
        };
    }
}

/// Shortcut method to quickly make a `GET` request.
///
/// See also the methods on the [`reqwest::Response`](./struct.Response.html)
/// type.
///
/// # Examples
///
/// ```rust
/// use std::io::Read;
///
/// # fn run() -> Result<(), Box<::std::error::Error>> {
/// let mut result = String::new();
/// reqwest::get("https://www.rust-lang.org")?
///     .read_to_string(&mut result)?;
/// # Ok(())
/// # }
/// # fn main() { }
/// ```
///
/// # Errors
///
/// This function fails if:
///
/// - native TLS backend cannot be initialized
/// - supplied `Url` cannot be parsed
/// - there was an error while sending request
/// - redirect loop was detected
/// - redirect limit was exhausted
pub fn get<T: IntoUrl>(url: T) -> ::Result<Response> {
    Client::new()
        .get(url)
        .send()
}

fn _assert_impls() {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}
    fn assert_clone<T: Clone>() {}

    assert_send::<Client>();
    assert_sync::<Client>();
    assert_clone::<Client>();

    assert_send::<Request>();
    assert_send::<RequestBuilder>();

    assert_send::<Response>();

    assert_send::<Error>();
    assert_sync::<Error>();
}
<commit_msg>fix doc link to RequestBuilder<commit_after>#![deny(warnings)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![doc(html_root_url = "https://docs.rs/reqwest/0.7.3")]

//! # reqwest
//!
//! The `reqwest` crate provides a convenient, higher-level HTTP Client.
//!
//! It handles many of the things that most people just expect an HTTP client
//! to do for them.
//!
//! - Uses system-native TLS
//! - Plain bodies, JSON, urlencoded, multipart
//! - Customizable redirect policy
//! - Proxies
//! - (TODO: Cookies)
//!
//! The `reqwest::Client` is synchronous, making it a great fit for
//! applications that only require a few HTTP requests, and wish to handle
//! them synchronously.
//!
//! ## Making a GET request
//!
//! For a single request, you can use the [`get`][get] shortcut method.
//!
//! ```rust
//! use std::io::Read;
//! # use reqwest::{Error, Response};
//!
//! # fn run() -> Result<Response, Error> {
//! let mut resp = reqwest::get("https://www.rust-lang.org")?;
//! assert!(resp.status().is_success());
//!
//! let mut content = String::new();
//! resp.read_to_string(&mut content);
//! # Ok(resp)
//! # }
//! ```
//!
//! As you can see, reqwest's [`Response`][response] struct implements Rust's
//! `Read` trait, so many useful standard library and third party crates will
//! have convenience methods that take a `Response` anywhere `T: Read` is
//! acceptable.
//!
//! If you plan to perform multiple requests, it is best to create a [`Client`][client]
//! and reuse it, taking advantage of keep-alive connection pooling.
//!
//! ## Making POST requests (or setting request bodies)
//!
//! There are several ways you can set the body of a request. The basic one is
//! by using the `body()` method of a [`RequestBuilder`][builder]. This lets you set the
//! exact raw bytes of what the body should be. It accepts various types,
//! including `String`, `Vec<u8>`, and `File`. If you wish to pass a custom
//! Reader, you can use the `reqwest::Body::new()` constructor.
//!
//! ```rust
//! # use reqwest::Error;
//! #
//! # fn run() -> Result<(), Error> {
//! let client = reqwest::Client::new();
//! let res = client.post("http://httpbin.org/post")
//!     .body("the exact body that is sent")
//!     .send()?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Forms
//!
//! It's very common to want to send form data in a request body. This can be
//! done with any type that can be serialized into form data.
//!
//! This can be an array of tuples, or a `HashMap`, or a custom type that
//! implements [`Serialize`][serde].
//!
//! ```rust
//! # use reqwest::Error;
//! #
//! # fn run() -> Result<(), Error> {
//! // This will POST a body of `foo=bar&baz=quux`
//! let params = [("foo", "bar"), ("baz", "quux")];
//! let client = reqwest::Client::new();
//! let res = client.post("http://httpbin.org/post")
//!     .form(&params)
//!     .send()?;
//! # Ok(())
//! # }
//! ```
//!
//! ### JSON
//!
//! There is also a `json` method helper on the [`RequestBuilder`][builder] that works in
//! a similar fashion the `form` method. It can take any value that can be
//! serialized into JSON.
//!
//! ```rust
//! # use reqwest::Error;
//! # use std::collections::HashMap;
//! #
//! # fn run() -> Result<(), Error> {
//! // This will POST a body of `{"lang":"rust","body":"json"}`
//! let mut map = HashMap::new();
//! map.insert("lang", "rust");
//! map.insert("body", "json");
//!
//! let client = reqwest::Client::new();
//! let res = client.post("http://httpbin.org/post")
//!     .json(&map)
//!     .send()?;
//! # Ok(())
//! # }
//! ```
//!
//! [hyper]: http://hyper.rs
//! [client]: ./struct.Client.html
//! [response]: ./struct.Response.html
//! [get]: ./fn.get.html
//! [builder]: ./struct.RequestBuilder.html
//! [serde]: http://serde.rs

extern crate bytes;
#[macro_use]
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
#[macro_use]
extern crate log;
extern crate libflate;
extern crate mime_guess;
extern crate native_tls;
extern crate serde;
extern crate serde_json;
extern crate serde_urlencoded;
extern crate tokio_core;
extern crate tokio_io;
extern crate tokio_tls;
extern crate url;
extern crate uuid;

pub use hyper::header;
pub use hyper::mime;
pub use hyper::Method;
pub use hyper::StatusCode;
pub use url::Url;
pub use url::ParseError as UrlError;

pub use self::client::{Client, ClientBuilder};
pub use self::error::{Error, Result};
pub use self::body::Body;
pub use self::into_url::IntoUrl;
pub use self::proxy::Proxy;
pub use self::redirect::{RedirectAction, RedirectAttempt, RedirectPolicy};
pub use self::request::{Request, RequestBuilder};
pub use self::response::Response;
pub use self::tls::{Certificate, Identity};

// this module must be first because of the `try_` macro
#[macro_use]
mod error;

mod async_impl;
mod connect;
mod body;
mod client;
mod into_url;
mod multipart_;
mod proxy;
mod redirect;
mod request;
mod response;
mod tls;
mod wait;

pub mod multipart;

/// A set of unstable functionality.
///
/// This module is only available when the `unstable` [feature][] is enabled.
/// There is no backwards compatibility guarantee for any of the types within.
///
/// [feature]: http://doc.crates.io/specifying-dependencies.html#choosing-features
#[cfg(feature = "unstable")]
pub mod unstable {
    /// An 'async' implementation of the reqwest `Client`.
    ///
    /// Relies on the `futures` crate, which is unstable, hence this module
    /// is **unstable**.
    pub mod async {
        pub use ::async_impl::{
            Body,
            Chunk,
            Decoder,
            Client,
            ClientBuilder,
            Request,
            RequestBuilder,
            Response,
        };
    }
}

/// Shortcut method to quickly make a `GET` request.
///
/// See also the methods on the [`reqwest::Response`](./struct.Response.html)
/// type.
///
/// # Examples
///
/// ```rust
/// use std::io::Read;
///
/// # fn run() -> Result<(), Box<::std::error::Error>> {
/// let mut result = String::new();
/// reqwest::get("https://www.rust-lang.org")?
///     .read_to_string(&mut result)?;
/// # Ok(())
/// # }
/// # fn main() { }
/// ```
///
/// # Errors
///
/// This function fails if:
///
/// - native TLS backend cannot be initialized
/// - supplied `Url` cannot be parsed
/// - there was an error while sending request
/// - redirect loop was detected
/// - redirect limit was exhausted
pub fn get<T: IntoUrl>(url: T) -> ::Result<Response> {
    Client::new()
        .get(url)
        .send()
}

fn _assert_impls() {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}
    fn assert_clone<T: Clone>() {}

    assert_send::<Client>();
    assert_sync::<Client>();
    assert_clone::<Client>();

    assert_send::<Request>();
    assert_send::<RequestBuilder>();

    assert_send::<Response>();

    assert_send::<Error>();
    assert_sync::<Error>();
}
<|endoftext|>